2012-04-28 76 views
1

我使用實體框架4.3SQLite的使實體之間許多一對多關係。但是在運行時,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) 
); 
+0

我應該指出,其他的東西很好的工作 - 加載表中的數據,一個一對多的關係,等等。 – Alex 2012-04-28 20:06:41

回答

2

要啓用延遲加載,請使導航屬性爲虛擬。例如:

public virtual ObservableCollection<Parameter> Parameters { get; set; } 

這樣,EF會在首次訪問數據庫時自動加載數據庫的集合。

如果你不想讓他們虛擬的或有延遲加載,那麼你可以在任何時候使用類似的顯式加載集合:

context.Entry(group).Collection(g => g.Parameters).Load(); 

或者,作爲加加建議,你可以急切地加載集合當你使用Inlcude數據庫的初始查詢:

context.Groups.Include(g => g.Parameters); 
0

你有什麼應該工作正常(我不知道的雖然SqlLite提供商的細節),

只需將其添加到查詢.Include(x=>x.Parameters)例如

db.Groups.Include(x=>x.Parameters) 

否則它是'懶惰'。