实体框架为相关对象创建新的/重复的条目 [英] Entity Framework Creates New / Duplicate Entries for Associated Objects

查看:145
本文介绍了实体框架为相关对象创建新的/重复的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Code First来创建一个SQL CE 4数据库。当运行下面的示例代码时,即使数据完全相同,Entity Framework每次都会为产品插入新的记录。 我需要做什么来使Entity Framework不会创建重复的关联产品? ForeignID1和Product对象中的值是数据库中已经存在的值,但实体框架正在擦除我给出的ID它添加一个新的ID。

I am trying to use Code First to create an SQL CE 4 database. When running the sample code below, Entity Framework is inserting new records for product each time, even though the data is exactly the same. What do I need to do to make Entity Framework not create duplicate associated products? The values in the ForeignID1 and the Product object are values that already exist in the database, but Entity Framework is wiping the ID I give it and adding a new ID.

namespace MyApp.Model
{
    public class MyThing
    {    
        public int ID { get; set; }

        [ForeignKey("Product")]
        public int ForeignID1{ get; set; }

        public virtual Product Product { get; set; }
    }
}

// Data.DataManager.cs

public class DataManager : DbContext
{
    public DbSet<Model.MyThing> Things{ get; set; }
    public DbSet<Model.Product> Products { get; set; }
}

这些是它输入的值。在表中应该只有一个值被多个 MyThings

These are the values it has entered. There should only be one value in the table that is referenced by multiple MyThings's

推荐答案

为了避免重复,您必须将相关实体附加到上下文中:

In order to avoid the duplication you must attach the related entity to the context:

context.Products.Attach(myThing.Product);
context.Things.Add(myThing);

或...

myThing.Product = null;
context.Things.Add(myThing);

...如果您设置了 myThing.ForeignID1 到现有的产品ID。

...will work as well if you have set myThing.ForeignID1 to an existing Product ID.

这篇关于实体框架为相关对象创建新的/重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆