简体   繁体   English

使用EF映射现有数据库中的关系

[英]Mapping relationships in existing database with EF

I am using an existing database that I am unfortunately unable to change, and seem to be having trouble creating a relationship. 我正在使用一个现有数据库,很遗憾,该数据库无法更改,并且似乎在建立关系时遇到了麻烦。 I'm relatively new to EF, and after some searches have found users trying to achieve something similar, however the advice given does not seem to work in this situation. 我是EF的新手,经过一些搜索发现用户试图实现类似的目标,但是给出的建议似乎在这种情况下不起作用。

I have the following classes: 我有以下课程:

public partial class Order
{
    public int Id { get; set; }
    public int BillingAddressId { get; set; }
    public int ShippingAddressId { get; set; }
    //more values

    public virtual Address ShippingAddress { get; set; }
    public virtual Address BillingAddress { get; set; }
}

public partial class Address
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    //more values
}

I'd like to be able to access the Shipping/Billing addresses through navigational properties within the order. 我希望能够通过订单中的导航属性访问收货/付款地址。 The ShippingAddressId / BillingAddressId fields both relate to Id in Address class but is unfortunately not set up in the database as a foreign key. ShippingAddressId / BillingAddressId字段都与Address类中的Id相关,但不幸的是未在数据库中设置为外键。

I believe the relationship I'm trying to achieve is many-one. 我相信我要建立的关系是一对多的。 ie An Order has one Shipping Address(Address), but an Address can be the Shipping Address of many Orders. 即,一个订单有一个送货地址(地址),但一个地址可以是许多订单的送货地址。

I've tried multiple variations of the following: 我尝试了以下多种变体:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    modelBuilder.Entity<Order>().HasOptional(o => o.ShippingAddress)
        .WithMany()
        .HasForeignKey(o => o.ShippingAddressId);

}

But every time I try to access Order.ShippingAddress.FirstName, I get a null reference exception. 但是每次我尝试访问Order.ShippingAddress.FirstName时,都会得到一个空引用异常。

Is what I'm trying to achieve possible? 我要实现的目标有可能吗?

If you have disabled lazy loading you will need to 'include' the navigation property in your query 如果您禁用了延迟加载,则需要在查询中“包含”导航属性

You can do this with one of the following: 您可以使用以下任一方法来执行此操作:

context.Orders.Include(o=>o.ShippingAddress).Where..... // make sure you are `using System.Data.Entity;`
context.Orders.Include("ShippingAddress").Where.....

in addition if your relationship is optional you will need to make the FK id nullable eg: 另外,如果您的关系是可选的,则需要使FK ID可为空,例如:

public int? BillingAddressId { get; set; }
public int? ShippingAddressId { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM