我正在处理一个现有的MVC项目。当我的上下文类继承自DBContext时,everythink很好,但当我将其更改为IdentityDbContext时,我得到了该错误。该行中出现错误: var makaleler = context.Makale.ToList();
我的控制员:
using mvcblogdeneme.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace mvcblogdeneme.Controllers
{
public class HomeController : Controller
{
// GET: Home
BlogDatabaseContext context = new BlogDatabaseContext();
public ActionResult Index()
{
return View();
}
public ActionResult CategoryWidgetGetir()
{
var kat = context.Kategori.ToList();
return View(kat);
}
public ActionResult TumMakalelerGetir()
{
var makaleler = context.Makale.ToList();
return View("MakaleListele", makaleler);//makalelistele bi partial view
}
}
}
这是我的模特:
namespace mvcblogdeneme.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Makale")]
public partial class Makale
{
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Baslik { get; set; }
[Required]
public string Icerik { get; set; }
public DateTime YayimTarihi { get; set; }
public int KategoriID { get; set; }
public virtual Kategori Kategori { get; set; }
}
}
答案 0 :(得分:0)
如果异常消息显示如下并且正在使用DbContext
:
EntityType' [[table name]]'没有定义键。定义密钥 这个EntityType。
EntityType:EntitySet' [[entity name]]'基于类型' [[表名]]' 没有定义键。
然后你肯定需要在KeyAttribute
属性上使用Id
将它标记为表模型类中的主键字段,问题将解决:
[Table("Makale")]
public partial class Makale
{
// if the ID also set as auto-increment, uncomment DatabaseGenerated attribute given below
// [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[Required]
[StringLength(150)]
public string Baslik { get; set; }
[Required]
public string Icerik { get; set; }
public DateTime YayimTarihi { get; set; }
public int KategoriID { get; set; }
public virtual Kategori Kategori { get; set; }
}
但是,如果发现原因来自IdentityDbContext
并且正在使用EF Code First,则需要执行以下步骤(归功于 DotNetHaggis ):
为IdentityUserLogin
创建配置类& IdentityUserRole
:
// taken from /a/20912641
public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
{
public IdentityUserLoginConfiguration()
{
HasKey(iul => iul.UserId);
}
}
public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
{
public IdentityUserRoleConfiguration()
{
HasKey(iur => iur.RoleId);
}
}
在OnModelCreating
方法中添加上述两个配置:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());
}
此时,由于已设置每个标识表的主键,因此应该解决错误。
类似问题: