EntityType 'MyProfile' has no key defined. ,怎么办?

  • 回答 (2)
  • 关注 (0)
  • 查看 (314)

我不知道为什么我会收到这个错误信息。我在SQL数据库中为它定义了一个主键。这是我的代码:

[HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

            if (createStatus == MembershipCreateStatus.Success)
            {

                FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                MembershipUser myObject = Membership.GetUser();
                Guid UserID = (Guid)myObject.ProviderUserKey;
                MyProfile profile = new MyProfile();
                profile.Address = model.Address;
                profile.City = model.City;
                profile.Zip = model.Zip;
                profile.State = model.State;
                profile.UserId = UserID;
                db.Profiles.Add(profile);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            }
        }

        // If we got this far, something failed, redisplay form
        ViewBag.PasswordLength = MembershipService.MinPasswordLength;
        return View(model);
    }

这是我的MyProfile类:

   namespace MatchGaming.Models
{
    [Bind(Exclude = "ProfileId")]
    public class MyProfile
    {
        [ScaffoldColumn(false)]
        public int ProfileId { get; set; }

        public Guid UserId { get; set; }

        [DisplayName("Address")]
        public string Address { get; set; }

        [DisplayName("City")]
        public string City { get; set; }

        [DisplayName("Zip")]
        public string Zip { get; set; }

        [DisplayName("State")]
        public string State { get; set; }


    }
}

我不知道为什么会有这个错误:EntityType 'MyProfile' has no key defined. Define the key for this EntityType.当它试图添加到数据库时db.Profiles.Add(profile);...

心尚未夜心尚未夜提问于
鸿鹄认真生活 做出美好的产品 App/VR/美国市场回答于
123456a134回答于

哪个字段是你的键?无论是ProfileId还是UserID,都可以将名称更改为MyProfileId或ID,或者将键属性在上面。

扫码关注云+社区

领取腾讯云代金券