2014-10-16 48 views
0

我對EF很新(基本剛起步)。我有以下問題。 可以說我有一張描述產品的表格,這個產品(基於類型)可以有多個額外的屬性(爲了這個查詢的目的,我將它限制爲兩個)。實體框架流暢的API映射爲零對一

class Product 
{ 
    [Key] 
    [Column("si_key")] 
    public Guid Key { get; set; } 

    [Column("si_Name")] 
    public string Name {get; set; } 

    [Column("si_Type")] 
    public TypeEnum Type { get; set; } 

    [Column("si_PaperType")] 
    public Guid? PaperType { get; set }; 

    [Column("si_FoilType")] 
    public Guid? FoilType { get; set }; 

    // Mappings 
    public PaperType PType { get; set; } 
    public FoilType FType { get; set; } 
} 

class FoilType 
{ 
    [Key] 
    [Column("ft_key")] 
    public Guid Key { get; set; } 

    [Column("ft_Name")] 
    public string Name {get; set; } 
} 

class PaperType 
{ 
    [Key] 
    [Column("pt_key")] 
    public Guid Key { get; set; } 

    [Column("pt_Name")] 
    public string Name {get; set; } 
} 

所以我們真的在談論0-1產品和(紙張和箔類型)之間的關係。

如何使用流暢的API定義它? 我試圖用:

modelBuilder.Entity<Product>() 
    .HasOptional(u => u.PType) 
    .WithOptionalPrincipal() 
    .Map(m => m.MapKey("pt_guid")); 

....

回答

0

,因爲它意味着雙方都是可選的,您不能使用WithOptionalPrincipal。

將關係配置爲可選:可選,在關係的另一側沒有導航屬性。正在配置的實體類型將成爲關係中的主體。關係所針對的實體類型將是依賴關係,並且包含對主體的外鍵。

你唯一的選擇就是所謂的1-1:

class PaperType 
{ 
    [Key] 
    [Column("pt_key")] 
    public Guid Key { get; set; } 

    [Column("pt_Name")] 
    public string Name {get; set; } 

    // Mappings 
    public Product Product { get; set; } 
} 

modelBuilder.Entity<Product>() 
    .HasOptional(x => x.PType) 
    .WithRequired(x => x.Product); 
+0

問題是,PaperType也可以由另一個實體,所以我不希望有一個產品導航性能(或列表)在另一邊。 – SebSky 2014-10-16 22:05:26

0
class Product 
{ 
    [Key] 
[Column("si_key")] 
public Guid Key { get; set; } 

[Column("si_Name")] 
public string Name {get; set; } 

[Column("si_Type")] 
public TypeEnum Type { get; set; } 

//[Column("si_PaperType")] 
//public Guid? PaperType { get; set };/* remove this line*/ 

//[Column("si_FoilType")] 
//public Guid? FoilType { get; set };/* remove this line*/ 

// Mappings 
public PaperType PType { get; set; } 
public FoilType FType { get; set; } 
} 


    modelBuilder.Entity<Product>() 
     .HasOptional<u.PType>(u => u.PType) 
     .WithOptionalDependent(c => c.Product).Map(p =>  p.MapKey("PTypeId"));