3

鉴于问题后面的代码,我从 EF4 代码优先 API 收到以下错误:

给定的属性“角色”不是受支持的导航属性。属性元素类型“IRole”不是受支持的实体类型。不支持接口类型。

基本上,我有一个类似于以下内容的存储库:

public class Repository : IRepository {
    private IEntityProvider _provider;
    public Repository(IEntityProvider provider) {
        _provider = provider;
    }
    public IUser GetUser(int id) {
        return _provider.FindUser(id);
    }
}

请注意,IRepository.GetUser 返回一个 IUser。

假设我的 IEntityProvider 实现看起来像这样。

public class EntityProvider : IEntityProvider {
    public IUser FindUser(int id) {
        /* Using Entity Framework */
        IUser entity;
        using (var ctx = new MyDbContext()) {
            entity = (from n in ctx.Users 
                  where n.Id == id 
                  select (IUser)n).FirstOrDefault();
        }
        return entity;
    }
}

这里的关键是 IUser 接口有一个名为 Roles 的 List<IRole> 属性。正因为如此,Entity Framework code-first 似乎无法确定使用哪个类来实现该属性所需的 IRole 接口。

下面是将在整个系统中使用并希望也与 EF4 一起使用的接口和 POCO 实体。

public interface IUser {
    int Id { get; set; }
    string Name { get; set; }
    List<IRole> Roles { get; set; }
}

public interface IRole {
    int Id { get; set; }
    string Name { get; set; }
}

public class User : IUser {
    public int Id { get; set; }
    public string Name { get; set; }
    public List<IRole> Roles { get; set; }
}

public class Role : IRole {
    public int Id { get; set; }
    public string Name { get; set; }
}

我会以错误的方式解决这个问题吗?有没有办法在 EF4 代码优先 API 中执行此操作?

我只能想到以下几点:

  1. EF4 代码优先使用的某种影子属性 (List<Role> DbRoles)。然后使用数据注释确保 EF4 忽略实际的 List<IRole>。
  2. 为 EF4 代码优先将使用的所有实体创建重复的类,然后将它们映射到实现接口的官方实体。
4

2 回答 2

2

Remember, you need to make the base classes abstract, (check out inheritance with EF documents for that), I recommend having a RootEntity with nothing in it, and then a Base entity with some common info, like Id, InsertedBy, UpdatedBy like standart fields, it makes everything much easier.

于 2011-05-05T18:39:03.130 回答
1

EF 4 Code First(从 CTP5 开始)不支持接口的使用,而且很可能在 RTM 中也不支持。我会说在你的 DbContext 中创建一个抽象类来保存你的对象。

于 2011-01-23T00:52:08.533 回答