2011-03-15 170 views
18

我不知道爲什麼我收到此錯誤消息。我有一個在我的sql數據庫中爲它定義的主鍵。這裏是我的代碼:EntityType'MyProfile'沒有定義密鑰。定義此EntityType的密鑰

[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); 
    } 

這是我的我的資料類:

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; } 


    } 
} 

我不知道爲什麼我收到此錯誤:當它試圖添加到數據庫db.Profiles.Add(profile);EntityType 'MyProfile' has no key defined. Define the key for this EntityType.

回答

36

哪個字段是你的鑰匙?無論是哪一種 - ProfileId或UserId - 將名稱更改爲MyProfileId或Id,否則在其上放置一個[Key]屬性。

1

我就遇到了這個問題,也和想補充一點,在實體框架6,因爲DbgGeography類型已經從組件System.Data.Entity的進入entityframework.dll移動出現此錯誤版本

解決這EF 6+刪除參考實體的dll和使用System.Data.Entity.Spatial

改變using語句來 看到這個http://entityframework.codeplex.com/workitem/1535

相關問題