I am trying to insert and update table using Entity Framework 6. I am not able to do it.
When i insert, I get an error
Unable to update the EntitySet 'SampleV2' because it has a DefiningQuery and no element exists in the element to support the current operation
When I update, the error thrown is:
The property 'Name' is part of the object's key information and cannot be modified.
My code:
//Table script
CREATE TABLE [dbo].[SampleV2](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](150) NOT NULL,
[DateOfBirth] [datetime] NOT NULL,
[Status] [bit] NOT NULL
) ON [PRIMARY]
// SampletV2.cs
public partial class SampleV2
{
public int Id { get; set; }
public string Name { get; set; }
public System.DateTime DateOfBirth { get; set; }
public bool Status { get; set; }
}
// Utilities.cs
public static Dictionary<bool,string> SavePlayerDetails(SampleV2 model)
{
Dictionary<bool, string> dicInfo = new Dictionary<bool, string>();
if (model.Id == 0)
{
try
{
SampleV2 sam = new SampleV2
{
Name = model.Name,
DateOfBirth = model.DateOfBirth,
Status = model.Status
};
using (var _context = new ExamEntities1())
{
_context.SampleV2.Add(sam);
_context.SaveChanges(); // getting error here
}
}
catch (Exception e)
{
throw;
}
}
else
{
try
{
using (var _context = new ExamEntities1())
{
SampleV2 data = _context.SampleV2.SingleOrDefault(a => a.Id == model.Id);
data.DateOfBirth = model.DateOfBirth;
data.Name = model.Name;
data.Status = model.Status;
_context.Entry(data).State = System.Data.Entity.EntityState.Modified; // getting error here
_context.SaveChanges();
}
}
catch (Exception e)
{
throw;
}
}
return dicInfo;
}
If you using Database First, the error indicates that the SampleV2
entity or table missing a primary key field or it is not being set in model class.
Try adding KeyAttribute
on id
entity to mark it as primary key field:
public partial class SampleV2
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public System.DateTime DateOfBirth { get; set; }
public bool Status { get; set; }
}
Additionally, you need to add primary key in DB using table designer with Set Primary Key
and setting StoreGeneratedPattern
as Identity
in EDMX file, then update generated model from database to ensure mapped entity class has identity primary key field.
NB: The KeyAttribute
can be generated automatically by editing T4 template (.tt
) file like this:
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
using System.ComponentModel.DataAnnotations;
// -- other stuff
var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
foreach (var edmProperty in simpleProperties)
{
if (ef.IsKey(edmProperty)) {
#> [Key]
<# }
#>
<#=codeStringGenerator.Property(edmProperty)#>
<#
}
}
Similar issues:
Entity Framework 4 Error: Unable to update the EntitySet because it has a DefiningQuery