How to map two One or Zero to One relationships

我是研究僧i 提交于 2019-12-12 05:06:02

问题


I have three entities with the name of SellinRequest, MortgageAndRent and Album. Each of SellinRequest and MortgageAndRent may have an Album.

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; }
}

This is the logic I want to be implemented:

  • (SellingRequest 1 .... 0-1 Album)
  • (MortgageAndRent 1 .... 0-1 Album)

With these mappings:

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

But I couldn't get the result. I don't know how to relate these two tables to Album table!


回答1:


Here is how I would do it w/o the fleunt syntax. Note the new id fields and that I marked the album properties as virtual

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; }
}


来源:https://stackoverflow.com/questions/40319809/how-to-map-two-one-or-zero-to-one-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!