Mapping with entity framework “code first”

给你一囗甜甜゛ 提交于 2019-12-08 04:52:59

问题


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;}
}

public 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?


回答1:


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.




回答2:


Your Address configuration does not connect address to city.




回答3:


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;}


来源:https://stackoverflow.com/questions/3858846/mapping-with-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!