c# - 在 Entity Framework 中查找或创建对象

标签 c# entity-framework

我的领域模型及其关联如下:

  • Customer 有很多Region
  • Region 有很多Location

我们的客户向我们提供了一个包含以下列的 CSV 文件:

  • 客户姓名
  • 地区名称
  • 地点名称
    • 纬度
    • 经度
    • ...

根据这些信息,我必须按名称查找或创建客户,按名称查找或创建区域,最后按名称查找或更新位置。

我尝试了以下方法:

var customer = from c in _data.Customer
               where c.Name == cells[0]
               select c;

if (customer == null)
    customer = new Customer(...);

我会遵循相同的模式来查找或创建/更新区域和位置,但是,我遇到的问题是 LINQ 查询的类型无法转换为 Customer 对象在线 customer = new customers();。稍后我需要引用这个 customer 对象,所以我不能有两个单独的变量。

我如何在 Entity Framework 中完成此操作?

最佳答案

这段代码

var customer = from c in _data.Customer
               where c.Name == cells[0]
               select c;

返回所有拥有 Name 的客户等于 cells[0]所以返回类型将是 IQueryable<Customer>不是单例Customer (这就是 customer = new Customer(...) 不起作用的原因)。

您需要的是调用FirstOrDefaultSingleOrDefault (取决于您的要求。)如果您想退回一个,就可以了 Customer .

所以这应该可行

var customer = (from c in _data.Customer
               where c.Name == cells[0]
               select c).SingleOrDefault();

关于c# - 在 Entity Framework 中查找或创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10892198/

相关文章:

c# - 方法 xx 和 yy 使用相同的 SOAPAction

C# 为什么创建新类时不需要继承对象类

c# - 线程安全 List<T>.Remove 创建的 System.ArgumentOutOfRangeException

c# - 在 linq to entities 中使用自定义方法

c# - 使用 LINQ 连接连接表中的列

c# - 访问 ListView CellTemplate UIElements

c# - 在asp.net中显示数据库中的Null

C# nameof 变成强类型参数?

wpf - 使用 SQLite 和 Entity Framework 进行数据绑定(bind)

c# - 使用 Entity Framework 6 代码优先注释映射 xmltype oracle