简体   繁体   English

首先,实体框架数据库,如何添加实体关联?

[英]Entity Framework DB first, How to add an entity association?

I am not sure if the question is worded properly but here is what I am trying to do. 我不确定问题的措词是否正确,但这是我想做的。

I am rewriting a VB.Net application where they were using linq-to-sql. 我正在重写使用linq-to-sql的VB.Net应用程序。 They used an object that had many of another object in it: 他们使用的对象中包含许多其他对象:

[Table(Name = "dbo.ParentTable")]
public class ParentTable : LINQEntityBase, INotifyPropertyChanging, INotifyPropertyChanged
{
    //Stuff

    //This Guy 
    [Association(Name = "ParentTable_ParentTableProperties", Storage = "_ParentTableProperties", ThisKey = "WQI_Key", OtherKey = "WQI_Key")]
    public EntitySet<ParentTableProperty> ParentTableProperties { get; set; }

    //More stuff
}

When I generate my DB first model there isn't actually a relationship in the database so what I end up with is all of the properties in the table without the properties 当我生成数据库第一个模型时,数据库中实际上没有任何关系,因此最终得到的是表中的所有属性,而没有属性

public partial class ParentTable
{
    //stuff

    //I need to add the EntitySet or an IEnumerable<ParentTableProperty> here but this is a generated class....

}

Most of my very limited experience in ORMS is with Fluent NHibernate. 我在ORMS中非常有限的经验大部分是使用Fluent NHibernate。 I am not sure how to add the relationship in code (I cannot edit the tables for reasons I can't go into here). 我不确定如何在代码中添加关系(由于无法进入此处的原因,我无法编辑表)。

A link to an article discussing this would be great. 链接到讨论此问题的文章将是不错的。 I am honestly not sure what I am trying to do is called (therefore my attempts at googleing were an epic failure). 老实说,我不确定我要做什么(因此我在Google上的尝试是史诗般的失败)。

Thanks to Robbin Cremers blog post I found a solution (I stress A SOLUTION because I don't know enough about this issue to say its the best one). 多亏了Robbin Cremers博客文章,我找到了一个解决方案(我强调一种解决方案,因为我对这一问题了解不足,无法说出最好的解决方案)。 Since Entity Framework uses partial classes to construct the objects from the database you can create your own customized object and add to the generated one: 由于Entity Framework使用局部类从数据库构造对象,因此您可以创建自己的自定义对象并将其添加到生成的对象中:

 //**********************
 //Blah blah blah 
 //This is generated code
 //Blah blah blah
 //***********************

 public partial class ParentTable
 {
      //stuff
 }

and then in a new file (so that if you regenerate your model it does not get overwritten): 然后在一个新文件中(这样,如果您重新生成模型,它就不会被覆盖):

 public partial class ParentTable
 {
     public virtual DbSet<ParentTableProperty> Properties { get; set; }
 }

and now at compile time it will be compiled to look like one class. 现在在编译时它将被编译为一个类。

 public class ParentTable
 {
     //stuff
     public virtual DbSet<ParentTableProperty> Properties { get; set; }
 }

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

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