如何使用代码优先框架添加对另一个现有实体的引用,而无需先从数据库中提取现有实体

发布于 2024-12-02 19:48:06 字数 633 浏览 5 评论 0原文

我正在尝试将现有产品附加到拍卖中,但如果不先从数据库中提取产品,则无法执行此操作。

这段代码可以工作,但是我如何只提供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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℉絮湮 2024-12-09 19:48:06

Auction 类中包含标量属性 ProductId

public class Auction
{
    public int Id {get;set;}
    public int ProductId {get;set;}
    public Product Product {get;set;}
    //other proerties
}

然后

auction.ProductId = 1;

db.Auctions.Add(auction);
db.SaveChanges();

Include the scalar property ProductId in the Auction class

public class Auction
{
    public int Id {get;set;}
    public int ProductId {get;set;}
    public Product Product {get;set;}
    //other proerties
}

Then

auction.ProductId = 1;

db.Auctions.Add(auction);
db.SaveChanges();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文