MVC的类创建主键字段 [英] Creating Primary Key field on MVC class

查看:1144
本文介绍了MVC的类创建主键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的MVC和C#。我只是偶然它,觉得它很有趣。我遇到这不会让我继续的问题。
这里是我的code:

I am new to MVC and C#. I just stumbled on it and found it interesting. I encountered an issue which will not allow me proceed. Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; 

namespace MyHotel.Models
{
    public class AccountTypes
    {
        public int AccountTypeID { get; set; }
        public string AccountTypeName { get; set; }
    }
}

我创建了CONTROLER,此后的看法。

I created the controler and the view thereafter.

和对于这一点,我一直得到这个错误:

And for this, I keep got this error:

模型生成过程中检测到一个或多个验证错误:

One or more validation errors were detected during model generation:

System.Data.Edm.EdmEntityType: : EntityType 'AccountTypes' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet "AccountTypes" is based on type "AccountTypes" that has no keys defined.

我谷歌的答案是超过了公众诠释AccountTypeID添加 [重点] {搞定;组; } 所以它看起来是这样的:

I google that the answers were to add [Key] over the public int AccountTypeID { get; set; } so it could look like this:

namespace MyHotel.Models
{
    public class AccountTypes
    {
        [Key]
        public int AccountTypeID { get; set; }
        public string AccountTypeName { get; set; }
    }
}

但没有结果,直到如今。
注:我使用MVC 4

But no result until now. Note: I am using MVC 4

推荐答案

实体框架codeFirst识别键,默认情况下,按名称。
有效的名称是编号< YourClassName方式>标识

Description

Entity Framework CodeFirst recognize the key, by default, by name. Valid names are Id or <YourClassName>Id.

您属性应该命名为编号 AccountTypesId

另一种方法是使用模型构建器来指定密钥。

Another way is to use the ModelBuilder to specify the key.

public class MyDbContext : DbContext
{
    public DbSet<AccountTypes> AccountTypes { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AccountTypes>.HasKey(x => x.AccountTypeID);
        base.OnModelCreating(modelBuilder);
    }
}

模式信息


  • Entity框架code教程首先

  • Mode Information

    • Entity Framework Code First Tutorial
    • 这篇关于MVC的类创建主键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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