0

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?

2
  • what was your last ef version ? and is it supposed to add FieldHeader Object Right ? Commented Oct 13, 2024 at 15:17
  • You went from ObjectContext to DbContext API. This error may only be the begin of what you have to do. Commented Oct 14, 2024 at 10:54

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.