0

我对 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 关系。

如何使用 fluent API 定义它?我试图使用:

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

……

4

2 回答 2

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);
于 2014-10-16T19:32:38.320 回答
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"));
于 2015-08-03T05:31:19.583 回答