实体框架流畅的API映射为零到一

时间:2014-10-16 19:01:45

标签: entity-framework ef-fluent-api

我是EF新手(基本上刚开始)。我遇到了以下问题。 假设我有一个描述产品的表,这个产品(基于类型)可以有许多其他属性(为了这个查询的目的,我将它限制为两个)。

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") );

...

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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"));
相关问题