开发者

Table with 2 foreign keys entity framework

开发者 https://www.devze.com 2023-03-22 20:15 出处:网络
I have a table which consists of 2 foreign keys. And those are only elements of the table. The table is meant to create association between 2 other tables. For example: The table is Users_Products, an

I have a table which consists of 2 foreign keys. And those are only elements of the table. The table is meant to create association between 2 other tables. For example: The table is Users_Products, and the only 2 columns are UserId and ProductID, both foreign keys. When I genera开发者_开发百科ted the EF object from database it didn't create Users_Products object, it only automatically created navigation properties. Now how can I insert data in my Users_Products table using EF?


You can get some user object and add product into its navigation property.

User user = context.Users.Where(u => u.Id == 1);
Product product = context.Products.Where(p => p.Id == 1);
user.Products.Add(product);
context.SaveChanges();


For code examples that show how to work with many-to-many relationships in EF see the Working with Many-to-Many Relationships section in The Entity Framework 4.0 and ASP.NET – Getting Started Part 5.

That is EF 4.0 / Database First; for an example using the DbContext API, see Adding Course Assignments to the Instructor Edit Page in Updating Related Data with the Entity Framework in an ASP.NET MVC Application (6 of 10).


using ( var ctx = new ...)
{
  var user = new User();
  var product = new Product();
  user.Products.Add(product);
  ctx.Users.AddObject(user);
  ctx.SaveChanges();
}


If you want to create relation (insert record to User_Products table) you just need to use navigation property either on User or Product:

user.Products.Add(product);

or

product.Users.Add(user);

That means you must have navigation property on at least one side to be able to create the relation. If you have loaded entities from the current contest you can use the approach described by @Pavel.

If you don't have loaded entities or if you don't want to do two queries to the database just to make a relation you can use this workaround:

// Make dummy objects for records existing in your database
var user = new User() { Id = 1 };
var product = new Product() { Id = 1 };
// Ensure that your context knows instances and does not track them as new or modified
context.Users.Attach(user);
context.Products.Attach(product);
// Again make relation and save changes
user.Products.Add(product);
ctx.SaveChanges();
0

精彩评论

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