我正在使用实体框架 4.3和SQLite在实体之间建立多对多关系。但在运行时,Group.Parameters 和 Parameter.Groups 集合是空的,直到我手动添加它们。
实体是:
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; }
}
在 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:
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)
);