I am using entity framework 4.3 with SQLite to make many-to-many relationship between entities. But in runtime, Group.Parameters and Parameter.Groups collections are empty, until i manually adds them.
Entities are:
public class Group
{
public Group()
{
Parameters = new ObservableCollection<Parameter>();
}
public Int64 Id { get; set; }
public string Name { get; set; }
public ObservableCollection<Parameter> Parameters { get; set; }
}
public class Parameter
{
public Parameter()
{
Groups = new ObservableCollection<Group>();
}
public Int64 Id { get; set; }
public string Name { get; set; }
public ObservableCollection<Group> Groups { get; set; }
}
In OnModelCreating:
modelBuilder.Entity<Group>().HasMany(g => g.Parameters).WithMany(p => p.Groups).Map(c =>
{
c.MapLeftKey("GroupId");
c.MapRightKey("ParameterId");
c.ToTable("Groups_has_Parameters");
});
sql for creating tables:
create table if not exists Parameters
(
Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Name TEXT NOT NULL
);
create table if not exists Groups
(
Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Name TEXT NOT NULL
);
create table if not exists Groups_has_Parameters
(
GroupId INTEGER NOT NULL,
ParameterId INTEGER NOT NULL,
PRIMARY KEY (GroupId, ParameterId),
FOREIGN KEY (GroupId) REFERENCES Groups(Id),
FOREIGN KEY (ParameterId) REFERENCES Parameters(Id)
);
To enable lazy loading make your navigation properties virtual. For example:
This way EF will automatically load the collection from the database the first time it is accessed.
If you don’t want to make them virtual or have lazy loading then you can explicitly load the collection at any time using something like:
Or, as Gaga suggested, you can eagerly load the collection when you do the initial query of the database using Inlcude: