如何将现有的实体集合添加到现有实体,而不需要首先使用代码优先框架从数据库中拉出现有实体 [英] How to add existing collection of entities to existing entity without pulling first pulling existing entities from database using code-first framework

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

问题描述

我正在尝试将现有和一个新的出价出价附加到现有的竞价中,但是如果没有先从数据库中提取产品,则无法执行此操作。

I'm trying to attach two existing and one new bid bid to an existing 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 bid id's for the existing bids and then save the auction

using (var db = new DataContext())
    //find existing auction
    var auction = db.Auctions.Find(1);

    var bid1 = db.Bids.Find(1);
    var bid2 = db.Bids.Find(2);
    var bid3 = new Bid()
    {
        //New Bid
    };

    //existing
    auction.Bids.Add(bid1);
    //existing
    auction.Bids.Add(bid2);
    //new
    auction.Bids.Add(bid3);
    db.SaveChanges();
}

编辑 - 我也尝试过,但是有一个参照完整性问题:以下innerexception:

EDIT - I tried this as well, but got a referential integrity problem: with the following innerexception:

{存储更新,插入或删除语句影响意外数量的行(0)。实体可能已被修改或删除,因为实体被加载刷新ObjectStateManager条目}

{"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."}

        using (var db = new DataContextContext())
        {
            var auction = db.Auctions.Find(1);
            var bid1 = new Bid() { BidId = 1 };
            db.Bids.Attach(bid1);
            auction.Bids.Add(bid1);
            db.SaveChanges();
        }


推荐答案

您可以使用附加以将已知实体添加到数据库上下文中。

You can use Attach to add known entities to the db context.

using (var db = new DataContext()) {
    //find existing auction
    var auction = db.Auctions.Find(1);
    var bid1 = new Bid() { BidId = 1 };
    var bid2 = new Bid() { BidId = 2 };

    var bid3 = new Bid()
    {
        //New Bid
    };

    //existing
    db.Attach(bid1);
    auction.Bids.Add(bid1);
    //existing
    db.Attach(bid2);
    auction.Bids.Add(bid2);
    //new
    auction.Bids.Add(bid3);
    db.SaveChanges();
}

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

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