我正在尝试在 Entity Framework 5.0 中使用有界 (Db) 上下文,但在从特定上下文中包含的类之一中排除属性时遇到问题。这是信息(为简洁起见,我将缩短)
BaseContext.cs
public class BaseContext<TContext> : DbContext where TContext : DbContext
{
static BaseContext()
{
Database.SetInitializer<TContext>(null);
}
protected BaseContext()
: base("name=Development")
{
}
}
IContext.cs
public interface IContext : IDisposable
{
int SaveChanges();
void SetModified(object entity);
void SetAdded(object entity);
}
ISuiteContext.cs
public interface ISuiteContext : IContext
{
IDbSet<Organizations> Organizations { get; set; }
...
}
SuiteContext.cs
public class SuiteContext : BaseContext<SuiteContext>, ISuiteContext
{
public IDbSet<Organizations> Organizations { get; set; }
...
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new OrganizationsConfiguration());
...
...
modelBuilder.Ignore<Colors>();
}
}
组织.cs:
public class Organizations
{
public Organizations()
{
Colors = new List<Colors>();
...
...
}
public int Organization_ID { get; set; }
public string Name { get; set; }
public string Address_1 { get; set; }
public string Address_2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public ICollection<Colors> Colors { get; set; }
...
...
}
组织配置.cs:
public class OrganizationsConfiguration : EntityTypeConfiguration<Organizations>
{
public OrganizationsConfiguration()
{
ToTable("Organizations");
HasKey(o => o.Organization_ID);
...
...
HasMany(o => o.Colors);
}
}
我如何使用(Web API 测试项目)
public class ValuesController : ApiController
{
private readonly IUnitOfWork _uow;
private readonly IOrganizationRepository _orgRepo;
public ValuesController()
{
_uow = new UnitOfWork<SuiteContext>(new SuiteContext());
_orgRepo = new OrganizationRepository(_uow);
}
// GET api/values
public IEnumerable<Organizations> Get()
{
return _orgRepo.RetrieveAll().AsEnumerable();
}
}
以及正在发生的异常:
导航属性“颜色”不是“组织”类型上声明的属性类型。验证它没有从模型中排除,并且它是一个有效的导航属性
我想要的只是让“SuiteContext”能够访问组织,但不能访问子项(颜色和其他一些)
我错过了什么?也许我错误地解释了异常?
更新#1
我试过(没有成功 - 同样的例外):
modelBuilder.Entity<Organizations>().Ignore(o =>o.Colors);
modelBuilder.Ignore<Colors>();
更新#2
我似乎与OrganizationsConfiguration.cs
类和HasMany()
方法有关。如果我取出HasMany(o => o.Colors)
,那么我可以按照我的意图忽略类/属性。但是,这也会导致数据库创建在重新创建时失败。如果我这样做该死,如果我不这样做该死!