Lau*_*ens 3 c# entity-framework
我的域模型及其关联如下:
Customer有很多RegionsRegion有很多Locations我们的客户向我们提供了一个包含以下列的CSV文件:
根据这些信息,我必须按名称查找或创建客户,按名称查找或创建区域,最后按名称查找或更新位置.
我尝试过以下方法:
var customer = from c in _data.Customer
where c.Name == cells[0]
select c;
if (customer == null)
customer = new Customer(...);
Run Code Online (Sandbox Code Playgroud)
我将遵循用于查找或创建/更新的区域和位置相同的图案,然而,我碰到的问题是,LINQ查询的类型不能被转换为Customer上线-object customer = new customers();.我需要customer稍后引用这个对象,所以我不能有两个单独的变量.
我将如何在实体框架中实现这一目标?
这段代码
var customer = from c in _data.Customer
where c.Name == cells[0]
select c;
Run Code Online (Sandbox Code Playgroud)
返回具有Name等于的所有客户,cells[0]因此返回类型将IQueryable<Customer>不是一个sigle Customer(这就是为什么customer = new Customer(...)不起作用).
你需要的是打电话FirstOrDefault或SingleOrDefault(根据你的要求),如果你想要的话Customer.
所以这应该工作
var customer = (from c in _data.Customer
where c.Name == cells[0]
select c).SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)