开发者

Entity Framework 4.1 Creating Duplicate Lookup Entries

开发者 https://www.devze.com 2023-02-22 01:51 出处:网络
I am using EF 4.1 code first.I have two classes: public class Product { public int ID { get; set; } public string Name { get; set; }

I am using EF 4.1 code first. I have two classes:

 public class Product {
      public int ID { get; set; }
      public string Name { get; set; }
      public int ProductTypeID { get; set; }
      public virtual ProductType ProductType { get; set; }
 }

 public class ProductType {
      public int ID { get; set; }
      public string Name { get; set; }
 }

If I have some existing ProductTypes that I have already created (IDs 2,3,4 for example), and I try to assign on one of those ProductTypes to a new product, it will create a duplicate of the Product type.

For example, if my greatest ProductTypeID is 4, and I run the following code, it will produce a duplicate:

 Expression<Func<ProductType, bool>> expr = s => s.ID == 2;
 ProductType t = DBContext.Set<ProductType>().Where(expr).First();
 Product p = new Product();
 p.ProductType = t;
 DBContext.Save开发者_开发知识库Changes();

This will actually create a new row in the "ProductType" table. The new ProductType will be identical to the one with ID 2, but it will have the new ID 5. All I am trying to do is associate the type with ID=2 to my new Product. Any idea what I am doing wrong?


This is actually a common mistake using EF.

You need to add the new product to DBContext:

Product p = new Product();
p.ProductType = t;
DBContext.AddObject(p); //here
DBContext.SaveChanges();


Why do you load ProdutType from database? You have foreign key exposed on your entity so this is what you need:

Product p = new Product();
p.ProductTypeId = 2;
DBContext.Products.Add(p);
DBContext.SaveChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消