2011-10-06 76 views
1

我有2個實體,每個實體都有一個相關的c#類。我在表上設置了導航屬性表A以包含對表B中的許多項目的引用。當我做一個新的表A類對象我需要能夠創建收集表B對象在表A。如何在表A c#class中設置導航屬性?在c#類中實現導航屬性

數據模型: http://bluewolftech.com/mike/mike/datamodel.jpg

+0

哪個EF的版本,您使用的?你使用Code First嗎?你有模型/圖表嗎? – CodingGorilla

+0

EF 4.0。是先使用代碼,然後使用數據模型的edmx文件。 – MBU

+2

如果您使用的是EDMX,則不會先使用代碼。第一個代碼只是用屬性裝飾的POCO類。 – CodingGorilla

回答

1

導航性能是EF簡單。下面的例子顯示了一個導航屬性是什麼樣子:

public class Foo 
{ 
    public int FooId { get; set; } 
    public string SomeProperty { get; set; } 

    public virtual IEnumerable<Bar> Bars { get; set; } 
} 

其中Foo代表TABLEA和Bar代表tableB的。他們關於導航屬性的關鍵詞是虛擬的,默認啓用延遲加載。假設您使用的是EF4.1 Code First。

編輯

關閉我的頭頂,這應該是一個很好的起點模板您:

public class PointOfInterestContext : DbContext 
{ 
    public IDbSet<PointOfInterest> PointOfInterest { get; set; } 
    public IDbSet<POITag> POITag { get; set; } 
    public IDbSet<Tag> Tag { get; set; } 

    public override OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     // custom mappings go here 
     base.OnModelCreating(modelBuilder) 
    } 
} 

public class PointOfInterest 
{ 
    // properties 
    public int Id { get; set; } 
    public string Title { get; set; } 
    // etc... 

    // navigation properties 
    public virtual IEnumerable<POITag> POITags { get; set; }  
} 

public class POITag 
{ 
    // properties 
    public int Id { get; set;} 
    public int PointOfInterestId { get; set; } 
    public int TagId { get; set; } 

    // navigation properties 
    public virtual PointOfInterest PointOfInterest { get; set; } 
    public virtual Tag Tag { get; set; } 
} 

public class Tag 
{ 
    // properties 
    public int Id { get; set; } 
    public string TagName { get; set; } 
    // etc... 

    // navigation properties 
    public virtual IEnumerable<POITags> POITags { get; set; }  
} 

那麼你會實現你的業務對象的其他邏輯。實體應該是輕量級的,至多應該有數據屬性。儘管如此,我更願意通過OnModelCreating使用流暢的映射。

這裏有一些很好的參考:
MSDN - EF 4.1 Code First
Code First Tutorial

+0

即時獲取「所需屬性'Foo'在類型'MyNamespace.Bar'上不存在。在Bar類中,我有一個屬性public virtual Foo Foo { get; set;}在edmx文件中的實體模型中,Bar實體上有一個導航屬性,它是Foo的一個實例,你知道那個錯誤可能是什麼嗎? – MBU

+0

@MBU如果你展示你的實體我會有一個更好的主意。 – shuniar

+0

如果OP使用EDMX,這會有什麼幫助嗎? –