EF4:保存对象子级
在数据库中,我有这些表:产品、请求和请求产品。 RequestProducts 是一张将多个产品链接到一个请求的表。
这是我的代码:
Product newProduct = new Product
{
Unity_ID = 3,
Quantity = 2,
Name = "toto",
AlreadyCurrency = true
};
Request newRequest = new Request
{
User_ID = 1,
CaseNumber = 1,
Draft = false
};
newRequest.Products.Add(newProduct);
_db.AddToProducts(newProduct);
_db.AddToRequests(newRequest);
_db.SaveChanges();
执行后,在我的数据库中我得到 1 个产品和 1 个请求。没关系,但是使用 newRequest.Products.Add(newProduct);
行创建的链接未在表 RequestProducts 中创建,但 EF4 通过向我建议 Products
列表来理解该链接在请求对象中。
是否可以仅使用此代码创建此链接?
谢谢你!
in database I have these tables: Product, Request and RequestProducts.
RequestProducts is a table to link many Product to one Request.
Here is my code:
Product newProduct = new Product
{
Unity_ID = 3,
Quantity = 2,
Name = "toto",
AlreadyCurrency = true
};
Request newRequest = new Request
{
User_ID = 1,
CaseNumber = 1,
Draft = false
};
newRequest.Products.Add(newProduct);
_db.AddToProducts(newProduct);
_db.AddToRequests(newRequest);
_db.SaveChanges();
After execute that, in my database I get 1 product and 1 request. It's ok, but the link create with line newRequest.Products.Add(newProduct);
is not created the table RequestProducts and yet EF4 understand the link by propose me the Products
list in the Request object.
Is it possible to create this link only with this code?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要额外的表来实现一对多关系。对于多对多关系,您只需要额外的表。
因此,在不知道您正在做什么以及原因的更多细节的情况下,我会说它工作正常。
理想情况下,您的 Request 对象将如下所示:
那么您的 Product 对象将如下所示:
You don't need an extra table for a one-to-many relationship. You'd only need that extra table for many-to-many relationships.
So, without knowing more specifics about what you're doing and why, I'd say it's working properly.
Ideally, your Request object would look something like:
Then your Product object would look like:
假设您使用 EDMX 生成的实体,您的
Product
表中应该有一个RequestId
FK 列。然后,在从数据库生成 EDMX 后,将不会有额外的表,因此您应该能够这样做:
更新
Request
(现在是Product
的属性)设置为newRequest
,然后当我将其添加到上下文(或如果已经添加),所有相关实体整个图表也会自动添加。Assuming you use generated entities of EDMX, you should have a single
RequestId
FK column in yourProduct
table.Then after you generate the EDMX from DB, there will not be additional tables, so you should then be able to do it this way:
Update
Request
(which is now a property of theProduct
) tonewRequest
, then when I add it to the context (or if it's already added), all the related entities of the whole graph will automatically be added too.