尝试将实体框架与asp.net MVC3一起使用

时间:2012-04-05 17:01:39

标签: asp.net-mvc-3 entity-framework

我正在尝试使用本教程使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”,因为connexionstring的上下文令人困惑......)

当我用代码运行我现在所拥有的东西时:

    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 ,没有定义键。

感谢您的帮助。

1 个答案:

答案 0 :(得分: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; }
    // ...
}