I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

How to pass Dbset object as a parameter to any user define function in entity framework code first?

I want to pass Dbset Object to my method.

This is my Method:

public static class MyClass
    {
       public static Floor ReturnObject(this DbSet<Floor> floor, int Id)
        {
           var context = floor.passContext() as MyDBContext;
           var data = context.floors.Where(a =>a.Id == Id).FirstOrDefault();
           return ad;
        }
     }

   public class MyDBContext: DbContext
    {
          public DbSet<Floor> floors { get; set; }
    }

public static DbContext passContext<TEntity>(this DbSet<TEntity> dbSet)
            where TEntity : class
        {
                 //code....
        }

Now i want to use my method of static class MyClass that is ReturnObject.

I want to use ReturnObject method in my Controller.

I know i can declare it as private member like this in my controller:

This is my controller:

public class MyController
{
       private DbSet<Floor> floor;//but is this a good way???
         public ActionResult Index(int Id)
            {
              var data=MyClass.ReturnObject(????,Id)//what should come in place of question mark??
            }
}

How should i pass my First Parameter to ReturnObject Method???

Upvotes: 1

Views: 2283

Answers (1)

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

Change your ReturnObject method. It should only take Id as parameter and filter data than return object of Floor.

public static Floor ReturnObject(int Id)
{
  using(MyDBContext context = new  MyDBContext())
  {
       var data = context.floors.Where(a =>a.Id == Id).FirstOrDefault();
       return ad;
   }
}

And when you call it than only pass id as paramter

var data=MyClass.ReturnObject(Id);

This will return object of floor which will be stored in data.

Upvotes: 1

Related Questions