首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >实体框架添加重复值

实体框架添加重复值
EN

Stack Overflow用户
提问于 2018-02-17 03:36:18
回答 1查看 32关注 0票数 0

我是EF的新手,我正在尝试与多对多的关系合作。

我有一个Developers表和一个Applications表。

每个开发人员可以有多个应用程序,每个应用程序可以有多个开发人员。

我曾尝试在StackOverflow上使用它提到要附加的示例,但我尝试了所有方法,但它仍然为应用程序创建了重复的开发人员。

代码语言:javascript
运行
复制
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都会创建一个新的开发人员与其关联。

代码语言:javascript
运行
复制
                context.Applications.Add(app);
                   // no matter what I try here I get a duplicate developer
                context.SaveChanges();
                return Ok(app.Id);

如有任何建议,我们将不胜感激!谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-17 04:01:02

更改:

代码语言:javascript
运行
复制
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;}
}

至:

代码语言:javascript
运行
复制
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>();
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48833688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档