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