EF 4 POCO:保存具有多个相关实体的新实体
假设我有以下 POCO 实体:
public class CellPhone {
public Manufacturer PhoneManufacturer;
public ICollection<Color> PhoneColor { get; set; }
public string Version { get; set; }
}
public class Manufacturer {
public int ID { get; set;}
public string Name { get; set; }
}
public class Color {
public int ID { get; set;}
public string Name { get; set; }
}
我的 ObjectContext 类中的每个实体都有一个 ObjectSet。
创建新的 CellPhone 实例时,我通常具有制造商和颜色的 ID,因此为了将新的 CellPhone 实例的引用添加到正确的制造商和颜色实体,我需要首先使用相同的上下文检索它们(查询它们的ObjectSet 为 ID),设置 CellPhone 实例的相关导航属性,然后保存新的 CellPhone 实例(将其添加到 ObjectSet 并 SaveChanges())。
如果我有超过 2 个与 CellPhone 这样的类相关的实体,这个过程就会变得效率低下。
有没有办法更有效地做到这一点?即无需查询数据库中的每个相关实体?
谢谢你的帮助。
简
Let's say I have the following POCO entities:
public class CellPhone {
public Manufacturer PhoneManufacturer;
public ICollection<Color> PhoneColor { get; set; }
public string Version { get; set; }
}
public class Manufacturer {
public int ID { get; set;}
public string Name { get; set; }
}
public class Color {
public int ID { get; set;}
public string Name { get; set; }
}
I have an ObjectSet for each of those entities in my ObjectContext class.
When creating a new CellPhone instance I usually have the IDs of both Manufacturer and Color, so in order to add a reference from my new CellPhone instance to the correct Manufacturer and Color entities, I need to first retrieve them using the same context (query their ObjectSet for the ID), set the relevant navigation properties of the CellPhone instance, and then save the new CellPhone instance (add it to the ObjectSet and SaveChanges()).
In case I have more than 2 related entities to a class like CellPhone this process becomes not efficient.
Is there a way to do it more efficiently? i.e. without querying the DB for each related entity?
Thank you for helping.
Jane
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将外键属性保留在模型类中。那么你不需要使用 Find by Id 。
现在你可以这样做,
you can keep the foreign key properties with your model class. Then you don't need to use Find by Id .
now you can do like this,