EntityType未定义键 [英] EntityType no keys defined

查看:87
本文介绍了EntityType未定义键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用,用户可以通过Facebook oAuth登录,然后设置歌曲列表.我收到以下错误消息:

I'm creating an app where users log in via Facebook oAuth and then set up a list of songs. I am getting the following error message:

BandFinderCsharp.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.

BandFinderCsharp.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.

IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.

IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.


我的SongsController中出现错误消息:

`namespace BandFinder.Controllers.Bread
{
    public class SongsController : Controller
    {
        private SongDBContext db = new SongDBContext();

        // GET: Songs
        public ActionResult Index()
        {
            return View(db.Songs.ToList()); <--- This is where the error occurs
        }

        // GET: Songs/Details/5
        public ActionResult Details(long? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Song song = db.Songs.Find(id);
            if (song == null)
            {
                return HttpNotFound();
            }
            return View(song);
        }

        // GET: Songs/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Songs/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,UserId,BandId,Title,Artist,Genre,ListId,CreatedOn")] Song song)
        {
            if (ModelState.IsValid)
            {
                song.CreatedOn = DateTime.Now;
                db.Songs.Add(song);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(song);
        }

        // GET: Songs/Edit/5
        public ActionResult Edit(long? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Song song = db.Songs.Find(id);
            if (song == null)
            {
                return HttpNotFound();
            }
            return View(song);
        }

        // POST: Songs/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,UserId,BandId,Title,Artist,Genre,ListId,CreatedOn")] Song song)
        {
            if (ModelState.IsValid)
            {
                db.Entry(song).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(song);
        }

        // GET: Songs/Delete/5
        public ActionResult Delete(long? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Song song = db.Songs.Find(id);
            if (song == null)
            {
                return HttpNotFound();
            }
            return View(song);
        }

        // POST: Songs/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(long id)
        {
            Song song = db.Songs.Find(id);
            db.Songs.Remove(song);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}`

我不明白的是,该控制器与IdentityUser代码无关.

The thing I don't understand is, this controller has nothing to do with the IdentityUser code..

这是我的ApplicationUser模型:

This is my ApplicationUser Model:

namespace BandFinderCsharp.Models
{
    public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
        {
            CreatedOn = DateTime.Now;
            this.ProfileImage  = new byte[0];
            this.facebookImage = new byte[0];
        }

        public byte[] facebookImage { get; set; }

        [MaxLength(32)]
        public string FirstName { get; set; }

        [MaxLength(32)]
        public string LastName { get; set; }

        public byte[] ProfileImage { get; set; }

        //public virtual ICollection<Instrument> Instruments { get; set; }
        //public virtual ICollection<Song> Songs { get; set; }
        //public virtual ICollection<Band> Bands { get; set; }

        public string Zipcode { get; set; }

        [Index]
        public float Longitude { get; set; }

        [Index]
        public float Latitude { get; set; }

        [Required]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public DateTime CreatedOn { get; set; }
        //////////////

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
            modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
            modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
            base.OnModelCreating(modelBuilder);
        }

        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}


为什么从歌曲控制器中引用身份模型时出现错误?此时两者之间应该没有任何关联.


Why am I getting an error referring to Identity models from the songs controller? There should be no correlation between the two at this point.

IdentityUser 类是内置的.NET类,我认为我无法

The IdentityUser class is a built in .NET class which I don't believe I'm able to edit:

namespace Microsoft.AspNet.Identity.EntityFramework
{
    //
    // Summary:
    //     Default EntityFramework IUser implementation
    public class IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>
    {
        //
        // Summary:
        //     Constructor which creates a new Guid for the Id
        public IdentityUser();
        //
        // Summary:
        //     Constructor that takes a userName
        //
        // Parameters:
        //   userName:
        public IdentityUser(string userName);
    }
}

IdentityUserLogin

namespace Microsoft.AspNet.Identity.EntityFramework
{
    //
    // Summary:
    //     Entity type for a user's login (i.e. facebook, google)
    public class IdentityUserLogin : IdentityUserLogin<string>
    {
        public IdentityUserLogin();
    }
}

推荐答案

如果ApplicationUser类是您要保存在数据库中的对象,则它必须包含一个名为Id的字段,该字段由默认为实体框架链接到的对象的主键.

If the ApplicationUser class is the object you're looking to save in the Data Base, then it must contain a field named Id which is by default the primary key of the object to which Entity Framework is linking to.

您的对象应如下所示:

public class ApplicationUser
{
    public int Id { get; set; }
    public string Name { get; set; }
}

或者,如果要将其他属性设置为对象的主键,则应在该字段上方添加[Key]属性-并且还需要添加System.ComponentModel.DataAnnotations命名空间:

Or if you want to set a different property as the primary key for the object, you should add the [Key] attribute above that field - and you'll also need to add the System.ComponentModel.DataAnnotations namespace:

public class ApplicationUser
{
    public int Id { get; set; }
    [Key]
    public string Name { get; set; }
}

这篇关于EntityType未定义键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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