asp.net-mvcentity-framework-6

Does not contain a definition for 'CreateObjectSet' and no extension method 'CreateObjectSet' in EF6


I am using Entity Framework 6 but the following code is throwing error. The code is migrated from old EF version where it is working fine.

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;

using (var context_ = new MyEntities())
{
        ObjectSet<FieldHeader> query = context_.CreateObjectSet<FieldHeader>(); /error on this line
        replaceField(query, dsSet.Tables[0]);
}

Error
Does not contain a definition for 'CreateObjectSet' and no extension method 'CreateObjectSet'

How can I use it in EF6?


Solution

  • as far as i know ObjectSet used to query, add, modify, and delete objects ,

    so you need to change your code for adding objects which should be suitable by Ef6 in Ef6 we used DbContext Apis

    public IDbSet<Report> Reports { get; set; }
    

    and also ObjectSet was replaced by DbSet but i suggested to change or o switch to the DbContext and DbSet for simpler replaceField function can be rewritten to work with DbSet. any way if you insest to keep your structure you could try these :

      DbSet<FieldHeader> query = context_.Set<FieldHeader>();
    
    replaceField(query, dsSet.Tables[0]);
    
    
    
    public void replaceField(DbSet<FieldHeader> query, DataTable dataTable)
    {
        foreach (DataRow row in dataTable.Rows)
        {
            int id = Convert.ToInt32(row["Id"]);
            string name = row["Name"].ToString();
            
            FieldHeader existingFieldHeader = query.FirstOrDefault(f => f.Id == id);
            
            if (existingFieldHeader != null)
            {
                existingFieldHeader.Name = name;
            }
            else
            {
                FieldHeader newFieldHeader = new FieldHeader
                {
                    Id = id,
                    Name = name
                };
                query.Add(newFieldHeader);
            }
        }
        
        context_.SaveChanges(); // Assuming context_ is your DbContext instance
    }