如何在首先从数据库中拉出现有实体之前,先使用代码优先框架添加对另一个现有实体的引用 [英] How do I add a reference to another existing entity using code-first framework without first pulling the existing entity from the database

查看:121
本文介绍了如何在首先从数据库中拉出现有实体之前,先使用代码优先框架添加对另一个现有实体的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

包含标量属性 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();

这篇关于如何在首先从数据库中拉出现有实体之前,先使用代码优先框架添加对另一个现有实体的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆