Resolved what is the alternative for DBSet.Create() method in Asp.net mvc Core?

Himasankar

Member
Joined
Jun 9, 2023
Messages
20
Programming Experience
5-10
I am migrating Asp.net mvc 5 application Asp.net Core. In this process I am facing DBSet.Create() method issue, it was exists in Asp.net mvc 5. But there is not Create method for DBset in Asp.net Core.


Thanks, Himasankar
 
DBSet.Create() has nothing to do with ASP.NET Core. That is an Entity Framework thing, not an ASP.NET Core thing.
 
Hi Sir, Still I am unable to solve my issue. I am providing my code here. Please check this and give me your suggestion.

Here, I would like to create record in database for that I am using below code.
I am using EF Core.
C#:
I was getting error in this line.       _set = _ORM.Set<object>();



     public  async void CreateEntity(BaseEntity model, String userAccount, Guid? ParentUniquId = null)
        {
       
            BaseEntity _model = null;
            EntityEntry _entry = null;

            try
            {
                //Adding the new model as shown below invokes EF's add management code.
                //That is a good thing.
                ////Create a new model.

        //GETTING ERROR HERE...

                _model = this.GetNewTrackedEntity();

                 ////Get the EF entry manager for the new model.
                 _entry = _ORM.Entry(_model);

                //Set the client model edit mode and changedBy to their actual values.
                model.ChangedBy = userAccount;
                model.UniqueId = model.UniqueId == Guid.Empty ? Guid.NewGuid() : model.UniqueId;
           
                //Set the values of the new model to the ones that were passed in.
                //Commented by prasad
                _entry.CurrentValues.SetValues(model);
                _entry.State = Microsoft.EntityFrameworkCore.EntityState.Added;

                try
                {
                 
                    //await _ORM.Set<Lookups.Models.Program>().AddAsync((Lookups.Models.Program)model);
              
                    var i = await _ORM.SaveChangesAsync();

                    String _tableName = EntityFramework.GetTableFullName(this.GetEntityType(),this._ORM);

        //BELOW COMMENTED CODE ALSO NOT CREATING RECORD IN DATABASE.
                   // var AuditLogItem = new RM.AuditLog()
                  //  {
                    //    UniqueId = Guid.NewGuid(),
                    //    ActionDate = DateTime.Now,
                   //     ActionName = "INSERT",
                  //      ActionPerformedBy = userAccount,
                  //      RecordId = model.UniqueId,
                  //      TableName = _tableName,
                  //      TableId = model.TableId,
                 //       ParentUniqueId = ParentUniquId
                 //   };
                 //   _ORM.AuditLogs.Add(AuditLogItem);
                  //  _ORM.SaveChanges();
                }
                catch (Exception ex)
                {
                    String _errMsg = ExceptionMgmt.GetExStackMsg(ex);
                    //Remove the entry from the change tracker.
                    ((IObjectContextAdapter)_ORM).ObjectContext.Detach(_entry.Entity);
                    throw;
                }

            }
            catch (DbEntityValidationException dbEVEx)
            {
                String _errMsg = ExceptionMgmt.GetDbEntValExMsg(dbEVEx);
                throw new Exception(_errMsg);
            }
            catch (Microsoft.EntityFrameworkCore.DbUpdateException dbUEx)
            {
                String _errMsg = ExceptionMgmt.GetExStackMsg(dbUEx);
                throw;
            }
            catch (Exception ex)
            {
                String _errMsg = ExceptionMgmt.GetExStackMsg(ex);
                throw;
            }
        }


  private BaseEntity GetNewTrackedEntity()
        {
            BaseEntity _model;

            try
            {
        //GETTING ERROR HERE...
                _model = (BaseEntity)EntitySet.EntityType;

                return _model;
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                throw;
            }
        }


  protected Microsoft.EntityFrameworkCore.DbSet<Object> EntitySet
        {
            get
            {
                Type _type;
                Microsoft.EntityFrameworkCore.DbSet<Object> _set;
            
               _type = this.GetEntityType(); // THIS TYPE IS GETTING FROM CONTROLLER CLASS. PLEASE THIS METHOD BELOW.
                _set = _ORM.Set<object>();
                return _set;
            }
        }

   protected override Type GetEntityType()
        {
            return typeof(Service); // Service IS ENTITY.
        }
 
Last edited by a moderator:
Why are you trying to get a DbSet<Object>? All C# objects are of type Object. Shouldn't you be getting something like DbSet<Service> or DbSet<BasicEntity>?

Right now your code feel a lot like ADO.NET code that you are trying to force fit into Entity Framework. You just seem to be using Entity Framework to avoid making the database connections and the SQL queries.
 
Why are you trying to get a DbSet<Object>? All C# objects are of type Object. Shouldn't you be getting something like DbSet<Service> or DbSet<BasicEntity>?

Right now your code feel a lot like ADO.NET code that you are trying to force fit into Entity Framework. You just seem to be using Entity Framework to avoid making the database connections and the SQL queries.

Hi, I tried as you suggested by changing DBSet<object> to DBSet<BaseEntity> but I am getting following error.

1686709462673.png


1686709392290.png
 
The error seems pretty self explanatory. You need a type that is is your model. Unfortunately, your code is pretty hard to read, so I can't easily figure out exactly what entities you intend to save in your database.

Also, please post your code as text in code tags. Screenshots are terrible way to share code.
 
The error seems pretty self explanatory. You need a type that is is your model. Unfortunately, your code is pretty hard to read, so I can't easily figure out exactly what entities you intend to save in your database.

Also, please post your code as text in code tags. Screenshots are terrible way to share code.

added BaseEntity to _ORM.Set():
  protected Microsoft.EntityFrameworkCore.DbSet<BaseEntity> EntitySet
        {
            get
            {
                Type _type;
                Microsoft.EntityFrameworkCore.DbSet<BaseEntity> _set;
                
               _type = this.GetEntityType();
                _set = _ORM.Set<BaseEntity>();
                return _set;
            }
        }

But I am getting following error.

Cannot create a DbSet for BaseEntity because this type is not included in the model for the context
 
This is a perfect example of not explaining your problem fully. ALWAYS explain what you're actually trying to achieve, not just how you're trying to achieve it.

It appears that you have a base controller class that all your controllers inherit and a base entity class that all your entities inherit and you are trying to write a single method in the base controller that all controllers can use to get a DbSet of a different entity. In that case, what you're doing cannot work. What you should do is make your base controller generic and the generic type parameter be of your base entity type. You can then get a DbSet<T> in that command base class. Each controller would fix T to be a different entity type so, when they call the generic method to get a DbSet<T>, they will be getting a set of the correct type.
 
Based on my post above, your entities might look like this:
C#:
public class EntityBase
{
    // ...
}

public class ThingEntity : EntityBase
{
    // ...
}
and your controllers might look like this:
C#:
public class ControllerBase<TEntity> where TEntity : EntityBase
{
    // ...
    
    public DbSet<TEntity> GetDbSet()
    {
        return dbContext.Set<TEntity>();
    }
}

public class ThingController : ControllerBase<ThingEntity>
{
    // ...
}
Now, if you create a ThingController instance and call GetDbSet on it, you'll get a DbSet<ThingEntity> back. It's much like when you create a List<string>, all the members of that object relate to type string and when you create a List<int> they all relate to type int.
 
Based on my post above, your entities might look like this:
C#:
public class EntityBase
{
    // ...
}

public class ThingEntity : EntityBase
{
    // ...
}
and your controllers might look like this:
C#:
public class ControllerBase<TEntity> where TEntity : EntityBase
{
    // ...
   
    public DbSet<TEntity> GetDbSet()
    {
        return dbContext.Set<TEntity>();
    }
}

public class ThingController : ControllerBase<ThingEntity>
{
    // ...
}
Now, if you create a ThingController instance and call GetDbSet on it, you'll get a DbSet<ThingEntity> back. It's much like when you create a List<string>, all the members of that object relate to type string and when you create a List<int> they all relate to type int.

Hi @jmcilhinney thanks for your quick reply. Actually I am struggling with this migration process from last week. I was struck here. I tried as you suggested making BaseEntity as Generic. But I am not able to get that. I am sending my source code here. If you don't mine, can you please check this base controller and baseentity from the source code?. I am seeking help to solve this Baseentity issue.

I'll also try here as you suggested in the recent post.


Areas\Lookups\Controllers => ProgramController.cs this is the contoller having Create method.

I am uploading source code folder to google drive.




Thanks for your help.
 
Based on my post above, your entities might look like this:
C#:
public class EntityBase
{
    // ...
}

public class ThingEntity : EntityBase
{
    // ...
}
and your controllers might look like this:
C#:
public class ControllerBase<TEntity> where TEntity : EntityBase
{
    // ...
  
    public DbSet<TEntity> GetDbSet()
    {
        return dbContext.Set<TEntity>();
    }
}

public class ThingController : ControllerBase<ThingEntity>
{
    // ...
}
Now, if you create a ThingController instance and call GetDbSet on it, you'll get a DbSet<ThingEntity> back. It's much like when you create a List<string>, all the members of that object relate to type string and when you create a List<int> they all relate to type int.

Hi @jmcilhinney, as you suggested I have updated my base controller like below, I'll get back to you once I complete changes in all my controllers.

C#:
public abstract class BaseLinkedEntityEditorController<TEntity> : BaseEditorController where TEntity : BaseEntity

    {}
 
Hi @jmcilhinney, as you suggested I have updated my base controller like below, I'll get back to you once I complete changes in all my controllers.

C#:
public abstract class BaseLinkedEntityEditorController<TEntity> : BaseEditorController where TEntity : BaseEntity

    {}

Hi @jmcilhinney I have updated basecontrollers to generic. Now I am able to load DBSet<TEntity>. But I am getting another error here. I would like to get TEntity from DBSet<TEntity>. So I am getting following error.

Error:
Cannot convert type Microsoft.EntityFrameworkCore.DbSet<TEntity> to TEntity

Any solution for this?

I really appreciate your suggestions.
 
The issue that constitutes the subject of this thread has been resolved, so you should mark the thread Resolved. If you have a new issue then you should create a new thread for that, pricing all the information relevant to that issue and nothing else.
 
Back
Top Bottom