问题
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