1

得到了一个非常困难的 EntityFramework Code First 问题。我会尽可能简单。

假设我们有 n 个类,现在让我们从 2 个开始

public class Person  
{   
    public string Name { get; set; }  
}



public class Address   
{  
    public string AddressLine1 { get; set; }  
    public string AddressLine2 { get; set; }  
}

现在,我想做的是能够使用单个字符串搜索域模型,即像 DbContext.Search("Foo") 之类的东西。该调用将在人员和地址表中搜索字符串匹配项,并返回一个包含人员和地址实体的列表。

不得不说我不完全清楚如何去做,但我正在考虑使用 DataAnnotations 来做这样的事情

public class Person  
{  
    **[Searchable]**  
    public string Name { get; set; }  
}



public class Address   
{  
    **[Searchable]**  
    public string AddressLine1 { get; set; }  
    **[Searchable]**  
    public string AddressLine2 { get; set; }  
}  

我在正确的轨道上吗?我应该改用 Fluent API 吗?反射?

任何和所有的想法都非常感谢。

4

2 回答 2

0

创建一个新的对象类型,您将在其上投影 2 种类型的搜索结果:

public class Result
{
    public string MainField { get; set; } 
    // you may have other properties in here.
}

然后找到符合您的条件的每种类型的实体,将它们投影到此类型上:

var personResults = DbContext.Persons
      .Where(p => p.Name == "Foo")
      .Select(p => new Result{MainField = p.Name}); 
      // don't forget to map to any other properties you have in Result as well


var addressResults = DbContext.Adresses
     .Where(a => 
        a.AddressLine1 == "Foo" ||  
        a.AddressLine2 == "Foo"
     ).
     .Select(a => new Result{MainField = a.AddressLine1 + ", " + a.AddressLine2 });
     // again, don't forget to map to any other properties in Result 

然后合并列表:

var allResults = personResults.Union(addressResults).ToList();

...此时您可以根据需要对列表进行排序。

“Result”和“MainField”,比较通用;只是使用它们,因为我不完全了解您的域模型。

于 2012-08-07T11:35:00.810 回答
0

the Find method searches only in the Primary Key column. If we don't make any column explicitly primary key column then find method will throw error. Generally EF convention takes propertyName+id as the primary key in the class. But if you want to search with Name then Make add [Key] to the property. it will become primary key and u will be able to find properties. dbContext.Addresses.find("Foo");

于 2012-08-07T11:01:14.440 回答