如何使用代码优先框架添加对另一个现有实体的引用,而无需先从数据库中提取现有实体
我正在尝试将现有产品附加到拍卖中,但如果不先从数据库中提取产品,则无法执行此操作。
这段代码可以工作,但是我如何只提供productid然后保存拍卖
var product = new Product()
{
//Known existing product id
ProductId = 1
};
var auction = new Auction
{
BuyItNowPrice = 10.
Product = product,
...
...
};
using (var db = new DataContext())
{
var product = db.Products.Find(auction.Product.ProductId);
auction.Product = product;
db.Auctions.Add(auction);
db.SaveChanges();
}
I'm trying to attach an existing product to an auction, but am unable to do so without first pulling the product from the database.
This code works, but how would I go about just providing the productid and then saving the auction
var product = new Product()
{
//Known existing product id
ProductId = 1
};
var auction = new Auction
{
BuyItNowPrice = 10.
Product = product,
...
...
};
using (var db = new DataContext())
{
var product = db.Products.Find(auction.Product.ProductId);
auction.Product = product;
db.Auctions.Add(auction);
db.SaveChanges();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
Auction
类中包含标量属性ProductId
然后
Include the scalar property
ProductId
in theAuction
classThen