How do I add a reference to another existing entity using code-first framework without first pulling the existing entity from the database
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.Produc开发者_运维知识库t.ProductId);
auction.Product = product;
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();
精彩评论