Ricevo il seguente errore quando provo a ottenere tutti i Suppliers
con Entity Framework 6.1.
La proprietà "Street" non è una proprietà dichiarata sul tipo "Indirizzo". Verificare che la proprietà non sia stata esplicitamente esclusa dal modello utilizzando il metodo Ignora o l'annotazione dati NotMappedAttribute. Assicurarsi che sia una proprietà primitiva valida.
Le mie entità assomigliano a questo:
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
}
}
Ho anche definito due mapping:
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();
}
}
Ma quando eseguo il codice seguente mi viene indicato l'errore sopra descritto:
using (var ctx = new DDDv1Context())
{
var aaa = ctx.Suppliers.First(); // Error here...
}
Il codice funziona quando rimuovo ICollection
dalla classe Supplier.cs
e rimuovo anche la classe di mapping dal mio contesto 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());
}
}
Perché il codice AddresMap
un errore quando provo ad usarlo con la classe Address
e la classe AddresMap
?
La tua proprietà Street è immutabile, deve avere un setter per far funzionare il tuo codice. Attualmente, non hai un setter definito su Street ed è per questo che stai ricevendo l'errore.