当我尝试使用Entity Framework 6.1获取所有Suppliers
时,我收到以下错误。
该物业' Street'不是类型'地址'的声明属性。 验证是否未明确排除该属性 通过使用Ignore方法或NotMappedAttribute数据注释来建模。确保它是有效的原始属性。
我的实体看起来像这样:
Supplier.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;
}
}
Address.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();
}
}
AddressMap.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...
}
当我从ICollection
类中删除Supplier.cs
并从我的db上下文中删除映射类时,代码可以正常工作:
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
类一起使用时,为什么代码会出错?
答案 0 :(得分:8)
您的Street属性是不可变的,它必须有一个setter才能使您的代码正常工作。目前,您还没有在Street上定义setter,这就是您收到错误的原因。