I'm getting the following error when I try to get all the Suppliers
with Entity Framework 6.1.
The property 'Street' is not a declared property on type 'Address'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property.
My entities look like this:
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
}
}
I also have two mappings defined:
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();
}
}
But when I run the following code I gives me the error described above:
using (var ctx = new DDDv1Context())
{
var aaa = ctx.Suppliers.First(); // Error here...
}
The code works when I remove the ICollection
from the Supplier.cs
class and also remove the mapping class from my db context:
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());
}
}
Why does the code give an error when I try to use it with the Address
class and AddresMap
class?
Your Street property is immutable, it has to have a setter for your code to work. Currently, you don't have a setter defined on Street and that's why you are getting the error.