我是EF的新手,我正在尝试与多对多的关系合作。
我有一个Developers表和一个Applications表。
每个开发人员可以有多个应用程序,每个应用程序可以有多个开发人员。
我曾尝试在StackOverflow上使用它提到要附加的示例,但我尝试了所有方法,但它仍然为应用程序创建了重复的开发人员。
public class Developer
{
public int DeveloperId { get; set; }
[Required]
public string DeveloperName { get; set; }
public virtual List<Application> Applications { get; set; }
}
public class Application
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Note { get; set; }
public Developer Owner { get; set;}
public virtual List<Developer> Developers { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Developer>()
.HasMany<Application>(d => d.Applications)
.WithMany(a => a.Developers)
.Map(ad =>
{
ad.MapLeftKey("DeveloperRefId");
ad.MapRightKey("ApplicationRefId");
ad.ToTable("DeveloperApplication");
});
}上面描述了我的设置。我尝试了很多方法,但每当添加新的应用程序时,EF都会创建一个新的开发人员与其关联。
context.Applications.Add(app);
// no matter what I try here I get a duplicate developer
context.SaveChanges();
return Ok(app.Id);如有任何建议,我们将不胜感激!谢谢!
发布于 2018-02-17 04:01:02
更改:
public class Application
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Note { get; set; }
public Developer Owner { get; set;}
}至:
public class Application
{
private List<Developer> _Developers;
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public string Note { get; set; }
[Required(ErrorMessage="The Id Of Owner(owner as a developer) is Required")]
public int DeveloperId { get; set; }
[ForeignKey("DeveloperId")]
public virtual Developer Owner { get; set;}
public virtual List<Developer> Developers { get{return _Developers;}} // This create Many to many
public application(){
_Developers= new List<Developer>();
}
}https://stackoverflow.com/questions/48833688
复制相似问题