How do I add a reference to another existing entity using code-first framework without first pulling the existing entity from the database

我们两清 提交于 2019-12-25 03:46:05

问题


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();
        }

回答1:


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();


来源:https://stackoverflow.com/questions/7286004/how-do-i-add-a-reference-to-another-existing-entity-using-code-first-framework-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!