简体   繁体   English

实体模型-如何插入/更新涉及导航属性的数据

[英]Entity Model - How to insert / update data which involves navigational properties

I am using Entity Framework, WebForms, .Net Framework 3.5 I want to update a record in database using entity model which involves updating a foreign key too, which has become a navigational property in Entity. 我正在使用Entity Framework,WebForms,.Net Framework 3.5,我想使用实体模型更新数据库中的记录,该模型也涉及到更新外键,外键已成为Entity中的导航属性。

How can I do that? 我怎样才能做到这一点? I have seen a way which involves another query like 我已经看到一种涉及另一个查询的方式

Product p = new Product{
   ID = 5,
   Name = "Bovril",
   Category = ctx.Categories.First( c => c.ID == 5)
};
ctx.AddToProducts(p);
ctx.SaveChanges();

How can I do that without going to DB ? 我如何在不使用DB的情况下做到这一点?

Try this (this works with EF 4 so hopefully it will work with EF 1 as well): 尝试以下操作(此方法可用于EF 4,因此希望它也可用于EF 1):

Category c = new Category 
{
    ID = 5
};
ctx.AttachTo("Categories", c);

Product p = new Product
{
   ID = 5,
   Name = "Bovril"
};
ctx.AddToProducts(p);

p.Category = c;
ctx.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架1-如何插入涉及导航实体的记录 - Entity Framework 1 - How to insert a record that involves Navigational Entities 阻止实体框架为导航属性插入值 - Prevent Entity Framework to Insert Values for Navigational Properties 所描述的数据模型的导航属性的实现 - Implementation of navigational properties for described data model 用于更新导航属性的通用数据访问层 - Generic Data Access layer to update navigational properties 如何测试涉及数据库中数据更新的业务逻辑层 - How to test business logic layer which involves data update in database 实体框架4抽象模型 - 如何以编程方式加载导航属性? - Entity Framework 4 Abstract Model - How to Programatically Eager-Load Navigational Properties? 使用实体框架时如何填充导航属性 - how to populate navigational properties when using Entity Framework 实体框架自定义导航属性 - Entity Framework Custom Navigational Properties 实体框架4每个层次结构表 - 如何定义儿童的导航属性? - Entity Framework 4 Table Per Hierarchy - How To Define Navigational Properties On Children? Entity Framework 6代码优先中的多维导航属性 - Multidimensional navigational properties in Entity Framework 6 Code First
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM