【发布时间】:2013-08-03 17:50:57
【问题描述】:
我有 80 个表的数据库(每个表都有主键)。我已经从数据库中生成了 ASP.NET MVC 项目中的模型(添加 - 新项目 - ADO.NET 实体数据模型)。但是在生成的模型中,我有 80 个类(对于数据库中的每个表)没有属性 [Key],例如:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Blog.Models
{
using System;
using System.Collections.Generic;
public partial class Comments
{
public int CommentId { get; set; }
public string Content { get; set; }
}
}
所以我有错误: EntityType xxx 没有定义键。定义此 EntityType 的键。
我经常更改数据库然后在项目中建模,所以 我不能每次都将 [Key] 属性添加到 80 个自动生成的类 - 我该怎么办??
【问题讨论】:
-
为什么在使用 DB-First 时需要
[Key]属性?该属性仅适用于 Code-First。对于 DB-First,所有元数据都取自 edmx 文件。你删除了这个文件吗?您是否更改了连接字符串并从那里删除了 edmx 引用? -
在 edmx 文件中,我将 PK 设置为 Identity,但在 Model.tt 下自动生成的文件中,我在类中没有属性 [Key]。
-
如前所述,预计模型没有 [Key] 属性。那么生成的上下文呢?它是否包含带有
UnintentionalCodeFirstException的OnModelCreating方法? -
是的,在自动生成的文件 Mode.Context.tt 我有方法:protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); }
-
您的 edmx 和模型是否在单独的类库项目中,如果是,您是否将连接字符串从库项目的
app.config复制到 mvc Web 项目中的web.config?
标签: asp.net-mvc entity-framework