2016-07-31 66 views
2

當我嘗試使用實體框架6.1獲取所有Suppliers時,出現以下錯誤。EF:屬性「街道」不是類型爲「地址」的聲明屬性

屬性「街道」不是「地址」類型的聲明屬性。 使用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... 
} 

代碼的工作,當我從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類用於代碼時會出現錯誤?

回答

5

您的街道屬性是不可變的,它必須有一個代碼才能工作。目前,您在街道上沒有定義設置者,這就是您遇到錯誤的原因。

+0

謝謝,那就是問題所在。然而,'Address'類是一個'ValueObject',應該是不可變的。爲了解決這個問題,我爲每個屬性添加了一個'protected set',而不是公共的。這似乎是訣竅。 – w00