实体框架添加重复值

时间:2018-02-16 19:36:18

标签: c# entity-framework

我是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);

任何建议都将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

变化:

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