用实体框架“首先编码”进行映射。 [英] Mapping with entity framework "code first"

查看:67
本文介绍了用实体框架“首先编码”进行映射。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用先编码的Entity Framework映射我的实体,但是映射复杂类型时遇到问题。这里是我的简化示例:

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:

域对象看起来像:

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

以及映射:

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

抛出的异常是:给定

有人可以帮我吗?

推荐答案

您正在尝试将站点实体类型添加到地址复杂类型。这是不可能的。
类似于实体,复杂类型由标量属性或其他复杂类型属性组成。由于复杂类型没有键,因此除了父对象之外,Entity Framework也无法管理复杂类型的对象。

看一下复杂类型文章了解更多信息。

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.

这篇关于用实体框架“首先编码”进行映射。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆