猿问

如何在实体框架中创建多对多映射?

在这种情况下,我有2个实体,例如Contract,Media。


public class Media : Entity

{

    public string Name {get; set;}

    public bool Enabled

    *//other properties can be ignored..*

}


public class Contract : Entity

{

    public string Code {get; set;}

    *//other properties can be ignored..*

}

合同有许多媒体,看来它们是多对多的。


但!!首先在EF代码,我需要在ContractMedia表(EF自动生成)中再添加3个字段。例如StartDate,EndDate和Price。无法将其添加到媒体实体中。


在这种情况下如何映射?


回首忆惘然
浏览 335回答 2
2回答

杨__羊羊

无需使用Fluent API,即可添加到@Tomas答案。public class Media // One entity table{&nbsp; &nbsp; public int Id { get; set; }&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public virtual ICollection<ContractMedia> ContractMedias { get; set; }}public class Contract // Second entity table{&nbsp; &nbsp; public int Id { get; set; }&nbsp; &nbsp; public string Code { get; set }&nbsp; &nbsp; public virtual ICollection<ContractMedia> ContractMedias { get; set; }}public class ContractMedia // Association table implemented as entity{&nbsp; &nbsp; [Key]&nbsp; &nbsp; [Column(Order = 0)]&nbsp; &nbsp; [ForeignKey("Media")]&nbsp; &nbsp; public int MediaId { get; set; }&nbsp; &nbsp; [Key]&nbsp; &nbsp; [Column(Order = 1)]&nbsp; &nbsp; [ForeignKey("Contract")]&nbsp; &nbsp; public int ContractId { get; set; }&nbsp; &nbsp; public DateTime StartDate { get; set; }&nbsp; &nbsp; public DateTime EndDate { get; set; }&nbsp; &nbsp; public double Price { get; set; }&nbsp; &nbsp; public virtual Media Media { get; set; }&nbsp; &nbsp; public virtual Contract Contract { get; set; }}
随时随地看视频慕课网APP
我要回答