MVC-EF逆向工程code首先包括另一个表 [英] MVC-EF Reverse Engineer Code first include another table

查看:246
本文介绍了MVC-EF逆向工程code首先包括另一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MVC-EF逆向工程code第一种模式,并且希望使用属性,包括另一个表。

I have an MVC-EF Reverse Engineer Code first model, and want to include another table using a property.

 public virtual OtherTableModel OtherTableModel{ get; set; }

但是当我这样做,我得到的错误:

However when I do this, I get the error:

显然,如果有EDMX有一个简单的方法来做到这一点。在这种情况下,这两个表有相同的主键:

Apparently if there is an edmx there is an easy way to do this. In this case, both tables have the exact same primary key:

string id {get; set} 

我怎样才能获得包括命令工作?

How can I get the include command to work?

在我的控制器code是:

In my controller the code is:

ourList = db.Table1.Include(t => t.OtherTableModel)

我得到的错误是:

The error I get is:

An exception of type 'System.InvalidOperationException' occurred in      
EntityFramework.SqlServer.dll but was not handled in user code

Additional information: A specified Include path is not valid. The 
EntityType Solution1.Models.User' does not declare a navigation property 
with the name 'OtherTableModel'.

请注意:我研究这个错误,但没有我发现答案是朝反向工程code第一种方法为目标。

NOTE: I have researched this error but none of the answers I found is geared toward the reverse-engineer code first approach.

在此先感谢!

推荐答案

您需要配置在表1的关系。 EF可以判断的关系,如果你的名字[表] + ID:

You need to configure the relationship in Table1. EF can determine the relationship if you name it [table] + Id:

public string OtherTableId {get; set;}
public OtherTableModel OtherTableModel {get; set;}

也可以添加注释:

or you can add annotations:

[ForeignKey("Id")]    
public OtherTableModel OtherTableModel {get; set;}

或者你可以使用流畅的API,我preFER:

or you could use the fluent API that I prefer:

public class Table1Configuration : EntityTypeConfiguration<Table1>
{
    public Table1Configuration()
    {
        HasRequired(p => p.OtherTableModel)
            .WithMany(p => p.Table1s)
            .HasForeignKey(p => p.Id)
            .WillCascadeOnDelete(false);
    }
}

这篇关于MVC-EF逆向工程code首先包括另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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