c#EF Model具有另一个模型的外键

时间:2017-03-01 20:52:41

标签: c# entity-framework

考虑以下两种模式:

public class Category
{
  public int Id {get;set;}
  public string Name {get;set;}
  public int Type {get; set;}
  ..other properties
}

public class Person
{
  public int PersonId {get; set;}
  public string Name {get; set;}
  public int CategoryId {get; set;}
  [ForeignKey["CategoryId"])
  public virtual Category Category {get; set;}
}

我有一个存储库类,它执行类似下面的操作,以使所有Person具有特定类型的类别:

var result = repo.FindBy<Person>(p=>p.Category.Type == 1).ToList()

Ivan要求的我的存储库方法:

 public IQueryable<T> FindBy<T>(Expression<Func<T, bool>> filter) where T : class
    {

            return _context.Set<T>().Where(filter).AsQueryable();
    }

我得到一个&#34;对象未设置为&#34; .Type属性上的错误,因为我认为它没有链接这两个模型。我相信这是因为外键不匹配(是否使用Reflection?)。 我无法将Category.Id重命名为数据库中的Category.CategoryId。 每当我通过在任一属性上设置数据注释从Person表中选择时,我可以在任何一个模型上做任何事情来链接类别吗?

0 个答案:

没有答案