我使用實體框架4.3與SQLite的使實體之間許多一對多關係。但是在運行時,Group.Parameters和Parameter.Groups集合是空的,直到我手動添加它們。EF4.3 + sqlite的許多一對多的關係
實體是:
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)
);
我應該指出,其他的東西很好的工作 - 加載表中的數據,一個一對多的關係,等等。 – Alex 2012-04-28 20:06:41