Home > Back-end >  How access SQLite Tables?
How access SQLite Tables?

Time:09-17

a question about EntityFramework and SQLite.

When I work with SQL Server and I want to do a query over a table I would access the required table (for example "Messages") very easily like so:

_databaseDBContext.Messages.where(m => m.id == id);

But on SQLite I can not access the table by simple entering the name, instead I have use the Set<>() method like so:

_SqliteDBContext.Set<Message>().where(m => m.id == id);

It got me thinking what would happen if I had two tables like:

DbSet<Message> Messages { get; set; }
DbSet<Message> OtheTypes { get; set; }

How can I do to properly indicate each other?

Thanks!

CodePudding user response:

The function .Set<T>() has an overload method that takes a table name; .Set<Message>(string name). So you can use that to differentiate between the two tables.

Where clause example:

var messages = _SqliteDBContext.Set<Message>("Messages").Where(x => x.id == 2);
var messages = _SqliteDBContext.Set<Message>("OtheTypes").Where(x => x.id == 2);

Example below using C# Query Language and the two database tables:

var query = from message in _SqliteDBContext.Set<Message>("Messages")
            join otherType in _SqliteDBContext.Set<Message>("OtheTypes") on messages.id equals otherType.id
            select new { message, otherType};

CodePudding user response:

EF Core only supports having one mapping in the model for each entity type. I.e. there aren't any supported cases in which two instance of the same type could end up being stored in different tables or different columns.

But you can do a simple trick:

public class Messagetwo : Message
{
}

And then in context

DbSet<Message> Messages { get; set; }
DbSet<Messagetwo> OtheTypes { get; set; }
  • Related