我有一个带有两个主键的表(和 Dto):int
和 string
类型:
public class Foo
{
public int Id { get; set; }
public string Data { get; set; }
// other members...
}
所以,我有一个 List<Dto> dtoList
,这是我从一个 DbContext 中得到的。我需要在其他 DbContext 中获得相同的 dto。问题是 PK 是一对两列。
这是我的做法(而且似乎行不通):
public IEnumerable<FooDto> GetFooByPrimaryKeys(List<int> ids, List<string> data)
{
return FooContext.Foo.Where(f => ids.Contains(f.Id) && data.Contains(f.Data));
}
但它返回了我需要的更多行。我的意思是,我传递了 1300 多对并获得了 1500 多对 dto,所以有些地方不对。
我不确定我是否采用了正确的方法。
您需要将int
和string
的唯一对 传递给该方法。您可以传入带有元组的单个列表,而不是传入两个单独的列表:
public IEnumerable<FooDto> GetFooByPrimaryKeys(List<Tuple<int, string>> keys)
{
return FooContext.Foo.Where(f => keys.Any(x => x.Item1 == f.Id && x.Item2 == f.Data));
}
如果 Entity Framework 无法处理这个问题,您可以选择获取所有记录,然后过滤已实现记录的内存列表:
public IEnumerable<FooDto> GetFooByPrimaryKeys(List<Tuple<int, string>> keys)
{
return FooContext.Foo.ToList().Where(f => keys.Any(x => x.Item1 == f.Id && x.Item2 == f.Data));
}
如果您有很多记录,您可能需要考虑编写一个存储过程:
How to pass an array into a SQL Server stored procedure
Passing an array/table to stored procedure through Entity Framework
无论如何,这里的主要问题是您需要与对 值进行比较。