Pet*_*ter 14 c# asp.net-mvc entity-framework asp.net-mvc-4
我是MVC和C#的新手.我偶然发现它并发现它很有趣.我遇到了一个不允许我继续的问题.这是我的代码:
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
之后我创建了控制器和视图.
为此,我一直有这个错误:
在模型生成期间检测到一个或多个验证错误:
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.
Run Code Online (Sandbox Code Playgroud)
我谷歌的答案是添加 [Key]
过来public int AccountTypeID { get; set; }
所以它可能看起来像这样:
namespace MyHotel.Models
{
public class AccountTypes
{
[Key]
public int AccountTypeID { get; set; }
public string AccountTypeName { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
但直到现在还没有结果.注意:我正在使用MVC 4
dkn*_*ack 20
实体框架CodeFirst默认情况下通过名称识别密钥.有效名称是Id
或<YourClassName>Id
.
您的财产应该命名Id
或AccountTypesId
另一种方法是使用ModelBuilder
指定键.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
50734 次 |
最近记录: |