开发者

Mapping with entity framework "code first"

I'm trying to map my entities using Entity Framework "code first", but I have a problem with mapping a complex type. Here my simplified exampled:

Domain object looks like:

public class Customer
{
    public Address DeliveryAddress {get; set;}
}

pub开发者_开发百科lic class Address
{
    public string StreetName {get; set;}
    public string StreetNumber {get; set;}
    public City City {get; set;}
}

public class City
{
    public int Id {get; set;}
    public string Name {get; set;}
}

and the mapping:

public class CustomerConfiguration : EntityConfiguration<Customer>
{
    public CustomerConfiguration()
    {
        this.HasKey(b => b.Id);
        this.Property(b => b.Id).IsIdentity();

        this.MapSingleType(x => new
        {
            Id = x.Id,
            DeliveryAddress_StreetName = x.DeliveryAddress.StreetName,
            DeliveryAddress_StreetNumber = x.DeliveryAddress.StreetNumber,
            DeliveryAddress_CityId = x.DeliveryAddress.City.Id, // this line causes an exception
        }).ToTable("Customer");
    }
}

public class AddressConfiguration : ComplexTypeConfiguration<Address>
{
    public AddressConfiguration()
    {           
        this.Property(b => b.StreetName).HasMaxLength(100).IsRequired().IsUnicode();
        this.Property(b => b.StreetNumber).HasMaxLength(6).IsRequired().IsUnicode();
}

public class CityConfiguration : EntityConfiguration<City>
{
    public CityConfiguration()
    {
        this.HasKey(b => b.Id);
        this.Property(b => b.Id).IsIdentity();
        this.Property(b => b.Name).IsRequired().HasMaxLength(200).IsUnicode();

        this.MapSingleType(x => new
        {
            Id = x.Id,
            Name = x.Name,
        }).ToTable("City");
    }
}

The exception that is being thrown is: 'The given key was not present in the dictionary.'

Can anyone help me?


You are trying to add Site Entity Type to Address Complex Type. This isn't possible. Like entities, complex types consist of scalar properties or other complex type properties. Because complex types do not have keys, complex type objects cannot be managed by the Entity Framework apart from the parent object.
Take a look at the Complex type article for more information.


Your Address configuration does not connect address to city.


The class reference is intended if you want to use Entity Frameworks navigation properties. To do that you should make class references virtual. So in Address the City property should be virtual. Also for ease of setting (especially if you are using MVC) you should include the ID value on the side that holds the reference like this

public virtual City City {get; set;}
public int CityId {get; set;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜