1

我正在尝试使用本教程使 EntityFramework 与 ASP .NET MVC3 一起工作:

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

好的,我有我的数据库、我的 .edmx 模型、模型类,但我没有得到的第一件事是:我的 DbContext 派生类怎么知道我的 .emdx 模型?我不知道在本教程中创建“链接”的位置(可能有几个具有相同名称“SchoolContext”的东西,因为连接字符串的上下文令人困惑......)

当我用代码运行我现在得到的东西时:

    MMContext context = new MMContext();

    List<EntityUser> testList = (from u in context.Users
                                select u).ToList();

我得到:

System.Data.Edm.EdmEntityType: : EntityType 'EntityUser' 没有定义键。定义此 EntityType 的键。

System.Data.Edm.EdmEntitySet: EntityType: EntitySet “Users” 基于没有定义键的类型“EntityUser”。

谢谢您的帮助。

4

1 回答 1

1

假设您使用的是 Code-First 方法,您必须在您的 Users 类中定义一个 Key:

public class User
{
    public int Id { get; set; }
    // ...
}

正如 Kyle 所述,如果您的 ID 字段未命名为“Id”,则必须添加[Key]属性:

using System.ComponentModel.DataAnnotations;
public class User
{
    [Key]
    public int u_Id { get; set; }
    // ...
}
于 2012-04-05T17:22:23.960 回答