EF:房产';街道';不是类型';的已声明属性;地址';
本文关键字:声明 地址 类型 属性 房产 街道 EF | 更新日期: 2023-09-27 17:59:33
当我尝试使用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();
}
}
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...
}
当我从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
类一起使用时,为什么代码会出现错误?
您的Street属性是不可变的,它必须有一个setter才能让您的代码工作。目前,您还没有在Street上定义setter,这就是为什么会出现错误的原因。