实体框架:没有导航属性映射外键 [英] Entity Framework: Map Foreign Key without Navigation Property?

查看:261
本文介绍了实体框架:没有导航属性映射外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动机:我的EF4.1 DbContext正在以不正确的顺序保存实体



原因:我的模型缺少导航属性



我想如何解决它:



我想在我的DbContext中设置外键关系。捕获是我的实体对象没有导航属性(我正在使用它来填充Web服务,然后将DTO对象发送到我的应用程序)。



下面的类将是一个例子。在MinorClass中,我想配置我的上下文,以便它知道MajorClassID是一个外键。我在互联网上发现的关于如何明确定义外键的文章涉及到使用导航属性,我的对象不具有。



有没有办法映射这种关系?

  public class MinorClass 
{
public Guid ID {get; set:}
public Guid MajorClassID {get; set;} //外键
public string Name {get; set;}
}

public class MajorClass
{
public Guid ID {get; set;}
public string Name {get; set;}
}


解决方案

导航属性是主要构造,而外键是助手(imho错误的帮手)。 EF通过由导航属性定义的关系识别DB命令的排序。你不能用外键定义关系。您至少需要关系一方的导航属性。


Motivation : My EF4.1 DbContext is saving Entities in the wrong order

Reason : Lack of navigation properties on my models

How I want to fix it :

I want to set up foreign key relationships in my DbContext. The catch is that my entity objects have no navigation properties (I'm using it to populate a web service and then firing DTO objects over to my application).

The classes below would be an example. In MinorClass, I want to configure my context so that it knows MajorClassID is a foreign key. The articles I've been finding on the internet on how to explicitly define Foreign Keys involve using navigational properties, which my objects dont have.

Is there a way to map this relationship?

public class MinorClass
{
    public Guid ID {get;set:}
    public Guid MajorClassID {get;set;} // foreign key
    public string Name {get;set;}
}

public class MajorClass
{
    public Guid ID {get;set;}
    public string Name {get;set;}
}

解决方案

Navigation property is primary construct whereas foreign key is helper (imho wrong helper). EF recognizes ordering of DB commands by relationships which are defined by navigation properties. You cannot define relation just by foreign key. You need navigation property on at least one side of the relation.

这篇关于实体框架:没有导航属性映射外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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