Reputation: 2708
I am using a database-first approach for Entity Framework. Below is my table. I have an identity column in my table, but when the dbcontext
class is created, it has entity.HasNoKey
in the OnModelCreating
method.
Below is the automatically generated code:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IdentityPersonalData>(entity =>
{
entity.HasNoKey();
entity.ToTable("Identity_PersonalData");
entity.Property(e => e.Address1)
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.Address2)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.City)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Email)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.FirstName)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.LastName)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.MiddleName)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.PhoneNumber)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.RecordId).ValueGeneratedOnAdd();
entity.Property(e => e.RequestType)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.State)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Status)
.HasMaxLength(50)
.IsUnicode(false);
entity.Property(e => e.Zip)
.HasMaxLength(50)
.IsUnicode(false);
});
OnModelCreatingPartial(modelBuilder);
}
When I tried to save the data to the database using the code below, I got this error:
Unable to track an instance of type 'IdentityPersonalData' because it does not have a primary key. Only entity types with primary keys may be tracked.
public void SaveData(IdentityPersonalData objPerson)
{
using (IdentityProofContext IdContext = new IdentityProofContext())
{
IdContext.IdentityPersonalData.Add(objPerson);
IdContext.SaveChanges();
Int64 id = objPerson.RecordId;
}
}
This is my class:
public partial class IdentityPersonalData
{
[Key]
public Int64 RecordId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string RequestType { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Status { get; set; }
}
I didn't have a [Key]
annotation over the recordId
. I put the key annotation later when I got this error that I mentioned above. I don't understand why am I getting an error if I already have a key and why the context class was created with entity.HasNoKey
.
Upvotes: 2
Views: 192
Reputation: 15161
You have explicitly specified that the model has no key at all when you added to the model builder
entity.HasNoKey();
Remove that and add
e.HasKey(s => s.RecordId);
Upvotes: 2