【问题标题】:EntityType 'MyProfile' has no key defined. Define the key for this EntityTypeEntityType 'MyProfile' 没有定义键。定义此 EntityType 的键
【发布时间】:2011-03-15 02:40:27
【问题描述】:

我不确定为什么会收到此错误消息。我在我的 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); 时。

【问题讨论】:

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


    【解决方案1】:

    哪个字段是您的关键?无论是 ProfileId 还是 UserId,要么将名称更改为 MyProfileId 或 Id,要么在其上添加 [Key] 属性。

    【讨论】:

      【解决方案2】:

      我也遇到了这个问题,并想在实体框架版本 6 中添加这个错误,因为 DbgGeography 类型已从程序集 system.data.entity 移动到 entityframework.dll 中

      要在 EF 6+ 中解决此问题,请删除对实体 dll 的引用并将 using 语句更改为 使用 System.Data.Entity.Spatial

      看到这个http://entityframework.codeplex.com/workitem/1535

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-02
        • 2016-03-16
        • 2013-08-04
        • 2012-12-10
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多