实体框架6在带有lambda表达式的where子句中使用parentid

时间:2016-03-15 10:31:04

标签: entity-framework lambda

我是EF的新手,想要通过以下方式从我的数据库(SQLite)获取一个条目:

类:

public class Customer
{
    public Guid Id { get; set; }
    public List<Month> Months { get; } = new List<Month>();
}

public class Month
{
    public int Id { get; set; }
    public string CacheId { get; set; }
    public string Data { get; set; }
    [Required]
    public Customer Customer { get; set; }
}

的DbContext:

public DbSet<Customer> Customers { get; set; }
public DbSet<Month> Months { get; set; }

用法:

using (var context = new CustomerContext())
{
  var customer = context.Customers.First();
  context.Database.Log = Console.WriteLine;
  var shouldContainOneEntry = context.Months.Where(x => x.Customer.Id == customer.Id).ToList();
}

shouldContainOneEntry是emtpy,但是使用委托和静态变量而不是lambda表达式的测试工作:

    private static Guid staticGuid;
    public static bool DelegateTest(Month x)
    {
        return staticGuid == x.Customer.Id;
    }
    ...
    staticGuid = customer.Id;
    var workingVersion = context.Months.Where(DelegateTest).ToList();

生成的SQL看起来正确:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[CacheId] AS [CacheId], 
[Extent1].[Data] AS [Data], 
[Extent1].[Customer_Id] AS [Customer_Id]
FROM [Months] AS [Extent1]
WHERE [Extent1].[Customer_Id] = @p__linq__0

-- p__linq__0: '5cfde6e0-5b3f-437b-84c8-2845b077462d' (Type = AnsiStringFixedLength, IsNullable = false)

为什么带有lambda表达式的版本不起作用?

2 个答案:

答案 0 :(得分:1)

通过遵循IvanStoev的提示找到解决方案。

SQLite默认以二进制格式存储Guid。 因此像

这样的查询
 SELECT * FROM Months WHERE CustomerId = '5cfde6e0-5b3f-437b-84c8-2845b077462d'

传递空结果。 使用SQLite Adminstrator,Guid以二进制格式显示。 使用VS中的服务器资源管理器,Guid会以字符串格式显示,这导致我得出错误的结论,这应该有效。

将连接字符串的选项BinaryGUID设置为false后,代码工作正常。

答案 1 :(得分:0)

根据您的声明

public class Customer
{
    public Guid Id { get; set; }
    public List<Month> Months { get; } = new List<Month>();
}

public class Month
{
    public int Id { get; set; }
    public Guid CustomerId{get;set;} // you need to add the foreign Key of the customer  ( i will suppose that your foreign key in db called CustomerId
    public string CacheId { get; set; }
    public string Data { get; set; } 
    [Required]
    [ForeignKey("CustomerId")] // and you need to tell EF which column is the foreign key
    public Customer Customer { get; set; }
}

现在如何使用

using (var context = new CustomerContext())
{
  var customer = context.Customers.First();
  context.Database.Log = Console.WriteLine;
  var shouldContainOneEntry = context.Months.Where(x => x.CustomerId == customer.Id).ToList();
}

希望它会帮助你