代码
我将向您展示代码,然后解释问题
接口(interface)
public interface IUser
{
Guid ID { get; set; }
string Name { get; set; }
ICollection<IRole> Roles { get; set; }
}
public interface IRole
{
Guid ID { get; set; }
string Name { get; set; }
}
请注意,接口(interface) IUser
定义 IRole 类型的 Roles 集合
实现
public class Role : IRole
{
public Guid ID { get; set; }
public string Name { get; set; }
}
public class User : IUser
{
public Guid ID { get; set; }
public string Name { get; set; }
public ICollection<IRole> Roles { get; set; }
}
EF Fluent API 配置
public class RoleConfiguration : EntityTypeConfiguration<Role>
{
public RoleConfiguration()
{
HasKey(p => p.ID)
.Property(p => p.ID);
Property(p => p.Name)
.IsRequired()
.HasMaxLength(70);
}
}
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
HasKey(p => p.ID)
.Property(p => p.ID)
.IsRequired();
Property(p => p.Name)
.HasMaxLength(60)
.IsRequired();
HasMany(r => r.Roles).WithMany();
}
}
注意配置EntityTypeConfiguration,其中T是实现而不是接口(interface)(EF不允许将接口(interface)作为T)
问题
#1 情况:
如果运行应用程序来生成关系模型,则会出现以下错误:
The navigation property 'Roles' is not a declared property on type 'User'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The navigation property 'Roles' is not a declared property on type 'User'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.
Source Error:
Line 58: public IQueryable<Project> GetAll(int pageIndex, int pageSize, params Expression<Func<Project, object>>[] includeProperties)
Line 59: {
Line 60: return includeProperties.Aggregate<Expression<Func<Project, object>>,
Line 61: IQueryable<Project>>(Context.Projects, (current, includeProperty) => current.Include(includeProperty)).OrderBy(p => p.Name).Skip(pageIndex).Take(pageSize);
Line 62: }
#2情况:
如果您注释掉 HasMany(r => r.Roles).WithMany();
行EF 将生成关系模型,User
之间没有关系。和Role
(应该是多对多)
我相信这是因为User
类中,有一个集合类型ICollection<IRole>
而不是 ICollection 类型。
问题
问题是,如何解决这个问题?
如何映射集合public ICollection<IRole> Roles { get; set; }
使用 Fluent API EF
最佳答案
CodeFirst 不支持映射接口(interface)。您需要更改它以引用 Role 具体类。
关于asp.net-mvc-3 - 使用接口(interface)和 EF Fluent API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8058398/