简体   繁体   English

从实体框架中的上下文中进行选择

[英]Selecting from context in Entity Framework

I am reading data from a Comma-separated Value (CSV) document and saving its contents to a database. 我正在从逗号分隔值(CSV)文档中读取数据并将其内容保存到数据库中。 Each row in the CSV file contains the following columns: CSV文件中的每一行都包含以下列:

  • Customer ID 顾客ID
  • Latitude 纬度
  • Longitude 经度

Our domain model is as follows: 我们的域名模型如下:

  • Customer has many Locations Customer有很多Locations
  • Location
    • Latitude 纬度
    • Longitude 经度

For each row, I am reading the Customer ID and look it up in the database: 对于每一行,我正在读取Customer ID并在数据库中查找:

var customer = (from c in Context.Customer
                where c.ID == id
                select c).SingleOrDefault();

If it does not exist, I create one: 如果它不存在,我创建一个:

if (customer == null)
{
    customer = new customers();
    customer.ID = id;
}

I do not save it at this point. 我此刻不保存。 Next, I create a new Location , and set its customer. 接下来,我创建一个新的Location ,并设置其客户。 Note that this customer may not actually be in the database yet. 请注意,此客户可能尚未真正进入数据库。

Now consider the following: if a customer is not yet in the database, I create one. 现在考虑以下内容:如果客户尚未加入数据库,我会创建一个。 But I do not save it yet. 但是我还没保存。 Now the next row belongs to the same customer that I just created, it is not yet in the database. 现在下一行属于我刚刚创建的同一个客户,它还没有在数据库中。 It will therefore create another customer. 因此,它将创造另一个客户。

When the time comes to save the graph to database, it will try to save two distinct customers with the same ID and fail. 当需要将图表保存到数据库时,它将尝试使用相同的ID保存两个不同的客户并失败。

How can I get Entity Framework to also select from what is in its context, even though it may not be persisted yet? 我如何让实体框架也从其上下文中选择,即使它可能还没有持久化?

First of all, you have to attach newly created entities to the context instance. 首先,您必须将新创建的实体附加到上下文实例。 Second, if you're using Code First, you can use DbSet.Find method - it can search for entities, which were not saved in store, but were already attached to context, without executing query to the store. 其次,如果您使用的是Code First,则可以使用DbSet.Find方法 - 它可以搜索未在商店中保存但已附加到上下文的实体,而不会对商店执行查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM