c# - EntityType 'MyProfile' 没有定义键。为此 EntityType 定义键

标签 c# asp.net asp.net-mvc-3

我不确定为什么会收到此错误消息。我在我的 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' 没有定义键。定义此 EntityType 的键。 当它尝试添加到数据库 db.Profiles.Add(profile); 时。

最佳答案

哪个领域是你的关键?无论它是什么 - ProfileId 或 UserId - 要么将名称更改为 MyProfileId 或 Id,要么在其上放置一个 [Key] 属性。

关于c# - EntityType 'MyProfile' 没有定义键。为此 EntityType 定义键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5306947/

相关文章:

ASP.NET Identity 2 在 cookie 身份验证后执行代码

c# - Response.Write() 和 Response.Output.Write() 有什么区别?

jquery - Bootstrap Datepicker 来自属性的开始日期

c# - MembershipService.ChangePassword 不更改密码问题

c# - 应用程序.Current.Shutdown();在未引用的程序集中定义

c# - 在 IIS8 中部署时缓存不起作用

asp.net - 我的 gacutil (vs2010 4.0) 似乎不起作用

c# - 从 WCF 返回 IObservable<T>

c# - 在 if 语句中检查多个字符串是否为 null

vb.net - VB 中 .NET MVC3 Razor View 中的命名空间引用?