0

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;
}
Venkateswaran R
  • 438
  • 2
  • 5
  • 18

1 Answers1

0

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:

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Entity Framework 4 Error: Unable to update the EntitySet because it has a DefiningQuery

Why am I getting a "Unable to update the EntitySet because it has a DefiningQuery..." exception when trying to update a model in Entity Framework?

Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • StoreGeneratedPattern already set into Identity only. KeyAttribute only not creating – Venkateswaran R Apr 04 '17 at 10:53
  • Thanks for your effect, after doing "Update Model from Database" also not changing Id field into KeyAttribute – Venkateswaran R Apr 04 '17 at 12:09
  • If your model generation using T4, I already give how to add `KeyAttribute` automatically every model update on EDMX file in latter part above. Check this doc for further details: http://stackoverflow.com/documentation/entity-framework/4414/database-first-model-generation/27049/adding-data-annotations-to-the-generated-model. – Tetsuya Yamamoto Apr 05 '17 at 00:40