2011-03-15 10 views
18

No estoy seguro de por qué recibo este mensaje de error. Tengo una clave principal definida en mi base de datos sql para ello. Aquí está mi código:EntityType 'MyProfile' no tiene una clave definida. Definir la clave para este 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); 
    } 

Y esta es mi MiPerfil Clase:

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


    } 
} 

No estoy seguro de por qué estoy recibiendo este error: EntityType 'MyProfile' has no key defined. Define the key for this EntityType. cuando se trata de añadir a la base de datos db.Profiles.Add(profile);.

Respuesta

36

¿Cuál campo es su clave? Cualquiera que sea - ProfileId o UserId - cambie el nombre a MyProfileId o Id o ponga un atributo [Key] en él.

1

me encontré con este problema también y quería añadir que en la versión de Entity Framework 6 se produce este error porque el tipo DbgGeography se ha movido de la system.data.entity montaje y en el entityframework.dll

para resolver esto en EF 6+ eliminar la referencia a la DLL entidad y cambiar la instrucción using a usando System.Data.Entity.Spatial

ver esto http://entityframework.codeplex.com/workitem/1535

Cuestiones relacionadas