我正在使用 Entity Framework 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)
);
最佳答案
要启用延迟加载,请使您的导航属性虚拟化。例如:
public virtual ObservableCollection<Parameter> Parameters { get; set; }
这样 EF 将在第一次访问时自动从数据库加载集合。
如果您不想将它们设为虚拟或延迟加载,那么您可以随时使用以下方式显式加载集合:
context.Entry(group).Collection(g => g.Parameters).Load();
或者,正如 Gaga 建议的那样,您可以在使用 Inlcude 对数据库进行初始查询时急切地加载集合:
context.Groups.Include(g => g.Parameters);
关于.net - EF4.3 + sqlite 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10366966/