MVC newbie
MVC newbie

Reputation: 599

MVC DbContext pull out all model

i am using Database first method. EDMX file generated default Dbset(TableName) for me.

myDbContext.Table1.ToList();
myDbContext.Table2.ToList();

Can we have a ModelView Class which pull both table out with single line? Instead of

Table1=myDbContext.Table1.ToList();
Table2=myDbContext.Table2.ToList();

can we have like

ModelView=myDbContext.ModelView;

Updated

  public partial class ProductTb
{
    public string ProductID { get; set; }
    public string ProductArticleNumber { get; set; }
    public string ProductName { get; set; }

}

  public partial class ProductTbTWO
{
    public string ProductID { get; set; }
    public string ProductArticleNumber { get; set; }
    public string ProductName { get; set; }

}

  public class ProductModelView
{
   public ProductTb{get;set;}
public ProductTbTWO{get;set}

}

Upvotes: 0

Views: 91

Answers (2)

Rudy
Rudy

Reputation: 464

i prefer using static class:

public static class Utilities
{
    public static ProductModelView getProductViewModel()
    {
        using (var db = new myDbContext()
        {
            var vm = new ProductModelView();
            vm.ProductTb = db.ProductTb.ToList();
            vm.ProductTbTWO = db.ProductTbTWO.ToList();
            return vm;
        }
    }
}

you can call it like:

var vm = Utilities.getProductViewModel();

Upvotes: 0

Ahmed
Ahmed

Reputation: 1590

Create a Partial Class of your DbContext and add your custom Code.

public partial  class MyDbContext 
{
   private MyDbContext(string contextName) : base(contextName) { }

   public static MyDbContextCreate() {
      return new MyDbContext(ContextName);
   }

   public ProductModelView ModelView {// Get ProductTb and ProductTbTWO}
}

and use it var myDbContext= MyDbContext.Create() and myDbContext.ModelView

But I don't recommend to do something like that, Add a Service class to with public method to get your code, Data Layer shouldn't deal with View Models

Upvotes: 1

Related Questions