【发布时间】:2016-07-31 12:12:28
【问题描述】:
当我尝试使用 Entity Framework 6.1 获取所有 Suppliers 时出现以下错误。
“Street”属性不是“Address”类型的声明属性。 验证该属性没有被明确排除在 使用 Ignore 方法或 NotMappedAttribute 数据注解建立模型。确保它是一个有效的原始属性。
我的实体如下所示:
供应商.cs:
public class Supplier : AggregateRoot
{
// public int Id: defined in AggregateRoot class
public string CompanyName { get; private set; }
public ICollection<Address> Addresses { get; private set; }
protected Supplier() { }
public Supplier(string companyName)
{
CompanyName = companyName;
Addresses = new List<Address>();
}
public void ChangeCompanyName(string newCompanyName)
{
CompanyName = newCompanyName;
}
}
地址.cs:
public class Address : ValueObject<Address>
{
// public int Id: defined in ValueObject class
public string Street { get; }
public string Number { get; }
public string Zipcode { get; }
protected Address() { }
protected override bool EqualsCore(Address other)
{
// removed for sake of simplicity
}
protected override int GetHashCodeCore()
{
// removed for sake of simplicity
}
}
我还定义了两个映射:
SupplierMap.cs
public class SupplierMap : EntityTypeConfiguration<Supplier>
{
public SupplierMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.CompanyName).IsRequired();
}
}
地址映射.cs
public class AddressMap : EntityTypeConfiguration<Address>
{
public AddressMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Street).IsRequired().HasMaxLength(50);
this.Property(t => t.Number).IsRequired();
this.Property(t => t.Zipcode).IsOptional();
}
}
但是当我运行以下代码时,我给出了上述错误:
using (var ctx = new DDDv1Context())
{
var aaa = ctx.Suppliers.First(); // Error here...
}
当我从 Supplier.cs 类中删除 ICollection 并从我的数据库上下文中删除映射类时,该代码有效:
public class DDDv1Context : DbContext
{
static DDDv1Context()
{
Database.SetInitializer<DDDv1Context>(null);
}
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<Address> Addresses { get; set; } //Can leave this without problems
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Configurations.Add(new SupplierMap());
// Now code works when trying to get supplier
//modelBuilder.Configurations.Add(new AddressMap());
}
}
当我尝试将代码与Address 类和AddresMap 类一起使用时,为什么代码会出错?
【问题讨论】:
标签: c# entity-framework entity-framework-6