【问题标题】:Customize table names ASP MVC 4自定义表名 ASP MVC 4
【发布时间】:2013-06-24 17:29:02
【问题描述】:

我以前在我的数据库中创建了一些表,我想将它们映射到一些模型类:

"SISTEMA.Voyages" => public class Voyage
"SISTEMA.Puerto"  => public class Port

我知道在带有实体框架的 ASP.MVC 4 中,这可以通过两种方式之一来完成。但是对于他们两个,我都遇到了我不知道如何解决的错误。

Voyage.cs 中的第一个:

[Table("SISTEMA.Voyages")]
public class Voyage

或者 Context.cs 中的第二个:

public class ApplicationEntities : DbContext
{
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Voyage>().ToTable("SISTEMA.Voyages");
  }
}

对于第一个版本,当我之前认为这是自动的时,我得到了这个错误:

The type or namespace name 'Table' could not be found (are you using directive or an assembly reference?)
The type or namespace name 'TableAttribute' could not be found (are you using directive or an assembly reference?)

我收到了这个我没想到的错误,因为我认为这是一个配置问题,让我很困惑:

The model backing the 'ApplicationEntities' context has changed since the database was created. Consider using Code First Migrations to update the Database.

这段历史记录在哪里?

为了记录,我习惯于在 Rails 中通过输入以下内容来处理此类问题:

class Voyage
    self.table_name = "SISTEMA.Voyages"
end

而且我对 C#/ASP.NET 不是很熟悉。只是发布我接下来一小时要查找的内容,除非有人先告诉我哪里出错了。

【问题讨论】:

  • 第一个版本你是否添加了 using 指令? (使用 System.ComponentModel.DataAnnotations)
  • 我刚做了。谢谢。我现在得到了第二种情况发生的错误。 :( 正在研究迁移,但我仍然感到困惑......
  • 阅读后更接近解决方案:stackoverflow.com/questions/3600175/… 基本上我添加了using System.Data.Entity;在Global.asax 中还添加了Database.SetInitilaizer&lt;DataContext&gt;(null);
  • 现在我只需要正确的语法,因为它被解释为dbo.SISTEMA.Voyages 而不是SISTEMA.Voyages

标签: asp.net-mvc-4


【解决方案1】:

对于第一种方式,您缺少 Table 属性的 using 指令,请将其添加到您的类中:

using System.ComponentModel.DataAnnotations;

对于第二种方式,我猜您的模型发生了一些变化,现在它建议使用 Code First 来更新数据库。当您运行您的应用程序时,它首先访问数据库,它会验证您的模型是否与架构匹配 - 如果不匹配,它会给您这个错误。

我建议您查看其中一些链接以获得 EF / Code First / Migrations 入门的帮助 - 它们真的很方便

EF + Code First
Handling Many to Many with Payload
How to work with Migrations
MSDN EF Site

【讨论】:

    【解决方案2】:

    请补充:

    使用 System.ComponentModel.DataAnnotations.Schema;

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      相关资源
      最近更新 更多