我正在尝试使用 Code First 创建一个 SQL CE 4 数据库。运行下面的示例代码时, Entity Framework 每次都会为产品插入新记录,即使数据完全相同。 我需要做什么才能使 Entity Framework 不创建重复的关联产品? ForeignID1 和 Product 对象中的值是数据库中已存在的值,但 Entity Framework 正在删除我提供的 ID它并添加一个新的 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
最佳答案
为了避免重复,您必须将相关实体附加到上下文:
context.Products.Attach(myThing.Product);
context.Things.Add(myThing);
或者...
myThing.Product = null;
context.Things.Add(myThing);
...如果您已将 myThing.ForeignID1
设置为现有产品 ID,也可以正常工作。
关于c# - Entity Framework 为关联对象创建新的/重复的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20710178/