如何映射两个One或Zero to One关系

时间:2016-10-29 13:56:52

标签: entity-framework ef-code-first entity-framework-6 mapping

我有三个名称为SellinRequest,MortgageAndRent和Album的实体。 SellinRequest和MortgageAndRent中的每一个都可能有一个专辑。

public class SellingRequest
{
    public int Id { get; set; }
    public Album Album { get; set; }  
}

public class MortgageAndRent
{
    public int Id { get; set; } 
    public Album Album { get; set; }
}

public class Album
{
    public int Id { get; set; }
    public SellingRequest SellingRequest { get; set; }
    public int SellingRequestId { get; set; }

    public MortgageAndRent MortgageAndRent { get; set; }
    public int MortgageAndRentId { get; set; }

    public List<Photo> Photos { get; set; }
}

这是我想要实施的逻辑:

  • (SellingRequest 1 .... 0-1专辑)
  • (MortgageAndRent 1 .... 0-1专辑)

使用这些映射:

public class SellingRequestMap : EntityTypeConfiguration<SellingRequest>
{
    public SellingRequestMap()
    {
        this.ToTable("SellingRequest");
        this.HasKey(sR => sR.Id);

        // Each SellingRequest may have one Album. (SellingRequest 1 .... 0-1 Album)
        this.HasOptional(sR => sR.Album).WithOptionalPrincipal(a => a.SellingRequest).WillCascadeOnDelete(false);
    }
}

public RentAndMortgageMap()
    {
        this.ToTable("MortgageAndRent");
        this.HasKey(mR=>mR.Id);

        // Each MortgageAndRent may have one Album. (MortgageAndRent 1 .... 0-1 Album)
        this.HasOptional(sM => sM.Album).WithOptionalPrincipal(a => a.MortgageAndRent).WillCascadeOnDelete(false);
    }

但我无法得到结果。我不知道如何将这两个表与相册表联系起来!

1 个答案:

答案 0 :(得分:0)

以下是我如何使用fleunt语法进行操作。请注意新的 id 字段,并将相册属性标记为虚拟

public class SellingRequest
{
    public int Id { get; set; }
    public int AlbumId {get;set;}

    public virtual Album Album { get; set; }  
}

public class MortgageAndRent
{
    public int Id { get; set; } 
    public int AlbumId {get;set;}

    public virtual Album Album { get; set; }
}

public class Album
{
    public int Id { get; set; }

    public int SellingRequestId { get; set; }   
    public int MortgageAndRentId { get; set; }

    public virtual SellingRequest SellingRequest { get; set; }
    public virtual MortgageAndRent MortgageAndRent { get; set; }

    public virtual List<Photo> Photos { get; set; }
}