MVC DbContext pull out all model - asp.net-mvc

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}
}

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

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();

Related

How do I implement an EFContextProvider using BreezeJS for .net core?

I have been able to implement Breeze into an angular application using AspNetCore based on the Breeze Temphire sample and the breeze.server.net/AspNetCore/ github samples. I am stuck trying to figure out how to implement EFContextProvider in a Unit Of Work. Referring to the Tempire Code Temphire on Github, can someone show me how to create a UnitOfWork using AspNetCore?
EFContextProvider does not exist in the following breeze libs:
Breeze.Core
Breeze.Persistence
Breeze.pErsistence.EFCore
Breeze.AspNetCore.NetCore
To be clear I would like to create the following using the AspNetCore/Breeze libs:
public class UnitOfWork
{
private readonly EFContextProvider<TempHireDbContext> _contextProvider;
public UnitOfWork()
{
_contextProvider = new EFContextProvider<TempHireDbContext>();
StaffingResources = new Repository<StaffingResource>(_contextProvider.Context);
Addresses = new Repository<Address>(_contextProvider.Context);
AddressTypes = new Repository<AddressType>(_contextProvider.Context);
PhoneNumbers = new Repository<PhoneNumber>(_contextProvider.Context);
PhoneNumberTypes = new Repository<PhoneNumberType>(_contextProvider.Context);
Rates = new Repository<Rate>(_contextProvider.Context);
RateTypes = new Repository<RateType>(_contextProvider.Context);
Skills = new Repository<Skill>(_contextProvider.Context);
States = new Repository<State>(_contextProvider.Context);
WorkExperienceItems = new Repository<WorkExperienceItem>(_contextProvider.Context);
StaffingResourceListItems = new StaffingResourceListItemRepository(_contextProvider.Context);
}
public IRepository<StaffingResource> StaffingResources { get; private set; }
public IRepository<Address> Addresses { get; private set; }
public IRepository<AddressType> AddressTypes { get; private set; }
public IRepository<PhoneNumber> PhoneNumbers { get; private set; }
public IRepository<PhoneNumberType> PhoneNumberTypes { get; private set; }
public IRepository<Rate> Rates { get; private set; }
public IRepository<RateType> RateTypes { get; private set; }
public IRepository<Skill> Skills { get; private set; }
public IRepository<State> States { get; private set; }
public IRepository<WorkExperienceItem> WorkExperienceItems { get; private set; }
public IStaffingResourceListItemRepository StaffingResourceListItems { get; private set; }
public SaveResult Commit(JObject changeSet)
{
return _contextProvider.SaveChanges(changeSet);
}
}
}
Could it be as simple as the following?
private readonly EFPersistenceManager<DictionaryPortalContext> _contextProvider;
Thanks!
Pretty close.
We usually create a separate class so that you have somewhere to add 'BeforeSaveEntities' and 'AfterSaveEntities' methods.
public class MyPersistenceManager : EFPersistenceManager<DictionaryPortalContext> {
public MyPersistenceManager (DictionaryPortalContext dbContext) : base(dbContext) {
// PM methods here.
}
and then
[Route("breeze/[controller]/[action]")]
[BreezeQueryFilter]
public class MyController : Controller {
private MyPersistenceManager PersistenceManager;
// called via DI
public MyController(NorthwindIBContext_CF context) {
PersistenceManager = new MyPersistenceManager(context);
}
[HttpGet]
public IActionResult Metadata() {
return Ok(PersistenceManager.Metadata());
}
[HttpPost]
public SaveResult SaveChanges([FromBody] JObject saveBundle) {
return PersistenceManager.SaveChanges(saveBundle);
}
...
}
Hope this helps.

Displaying data from two different model in a view

I am a newbie learning ASP.NET MVC from book.I am using NInject to Implement IoC. I have created a data model for Job and Location as below
Table Name - JobDetails
JobId<PK>
LocationId<FK>
JobName
Table Name - Location
LocationId<PK>
LocationName
I have created Entities for Location and JobDetails as Below
JobDetails
public class JobDetails
{
[Key]
public int JOBID { get; set; }
public int LocationID { get; set; }
public string JOBNAME { get; set; }
}
Location
public class Location
{
[Key]
public int LocationID{ get; set; }
public string LocationName { get; set; }
}
Also I have my Abstract and Context Class for Job Details and Location as below
public interface IJobDetails
{
IEnumerable<JobDetails> jobDetailsInterface { get; }
}
public interface ILocation
{
IEnumerable<Location> locationInterface { get; }
}
public class EFLocationRepository : ILocation
{
public EFDbContext context = new EFDbContext();
public IEnumerable<Location> locationInterface
{
get { return context.Location; }
}
}
public class EFJobRepository : IJobDetails
{
public EFDbContext context = new EFDbContext();
public IEnumerable<JobDetails> jobDetailsInterface
{
get { return context.JobDetails; }
}
}
My Model class for Job and Location are as below
public class JobListViewModel
{
public IEnumerable<JobDetails> jobDetails { get; set; }
}
public class LocationListViewModel
{
public IEnumerable<Location> Location { get; set; }
}
In my JobDetail Controller I want to display the location name instead of Location Id.
My JobDetail controller is as below
public class JobController : Controller
{
public IJobDetails repository;
public JobController(IJobDetails job)
{
repository = job;
}
public ViewResult List()
{
return View(repository.jobDetailsInterface);
}
}
How to display Location Name instead of Location id in my Job View?
N.B-I am learning MVC from Adam Freeman book and trying to create something new.Please let me know what I have done is correct or not.
Adding to sleeyuen's response. You may want to add a "navigation" property to JobDetails model, like below:
public class JobDetails
{
[Key]
public int JOBID { get; set; }
public int LocationID { get; set; }
public string JOBNAME { get; set; }
public virtual Location JobLocation { get; set; }
}
Then you should be able to access Location name from view by doing: repository.jobDetailsInterface.JobLocation.LocationName
In your scenario I believe entity framework will be able to infer relationships from the model structure, so you won't need entity configuration set up
Please note, this approach leads to N+1
Hope this helps :)

How to use table created using TPH in entity framework?

Domain Model
public abstract class BaseClass
{
public int Id { get; set; }
public int Something1 { get; set; }
public int Something2 { get; set; }
public string Something3 { get; set; }
}
public class PQR1 : BaseClass
{
public int value1 { get; set; }
}
public class PQR2 : BaseClass
{
public int value2 { get; set; }
}
public class PQR3 : BaseClass
{
public int value2 { get; set; }
}
Context Class
public class PQRContext : DbContext
{
public PQRContext() : base ("PQR")
{
}
public DbSet<BaseClass> Baseclass { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BaseClass>().
Map<PQR1>(m => m.Requires("Type").HasValue("Value1"))
.Map<PQR2>(m => m.Requires("Type").HasValue("Value2"))
.Map<PQR3>(m => m.Requires("Type").HasValue("Value3"));
}
}
It'll create table like this:
But I don't know how to use this table while coding, I get stuck like this
So I can't access to another classes like PQR1, PQR2,PQR3 where as I have no reason to insert data into base class which is already abstract.
First option :
You are not restricted on DbSet creations. You can create many DbSet as much as you need for your derived classes like the code below and access them like you will do with other DbSet :
public DbSet<BaseClass> Baseclass { get; set; }
public DbSet<PQR1> PQR1s { get; set; }
public DbSet<PQR2> PQR2s { get; set; }
public DbSet<PQR3> PQR3s { get; set; }
You use the DbSet related to the derived you want for inserting into or requesting your context.
Second option :
For querying your context and get only the desired subclass entities you can use the generic method OfType<T> which act as a filter like this:
var myBaseClassList = myContext.BaseClass; // Retrieve all PQR1, PQR2 and PQR3 entities
var myPQR1List = myContext.BaseClass.OfType<PQR1>(); // Retrieve all PQR1
var myPQR2List = myContext.BaseClass.OfType<PQR2>(); // Retrieve all PQR2
var myPQR3List = myContext.BaseClass.OfType<PQR3>(); // Retrieve all PQR3
For inserting you can create an instance of your derived class and add it directly to your base class DbSet :
var pqr1 = new PQR1() { /* set my properties */ };
myCOntext.BaseClass.Add(pqr1); // EF knows how to insert data for classes that use TPH.

.NET MVC -- Using Composition in a View Model

I am trying to wrap my head around the idea of Composition. Never used it before. I have a class that looks like this (thinned down):
public class AccountProfile
{
public string AccountNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public void GetAccountProfile()
{
AccountNumber = "123456"; // eventual these will become values from the database
FirstName = "John";
LastName = "Smith";
}
}
Then, in my view model, I'd like to have access to AccountNumber, FirstName, and LastName. I don't want to use inheritance, as this view model will need access to multiple external, unrelated classes. So far the model is simple:
public class AccountProfileViewModel
{
public AccountProfileViewModel() { }
}
Here's what I've tried so far, none which are correct:
public class AccountProfileViewModel
{
AP= new AccountProfile();
public AccountProfileViewModel() { }
}
That one (above) throws multiple errors and won't compile. I've also tried this:
public class AccountProfileViewModel
{
public AccountProfile AP { get; set; }
public AccountProfileViewModel() { }
}
This one (the one above) compiles just fine, but it throws a run-time error in the controller when I try and use it:
model.AP.GetAccountProfile();
The error: {"Object reference not set to an instance of an object."}
I'm out of ideas. Thanks!
you have to initialize the object at least.
public class AccountProfileViewModel
{
public AccountProfile AP { get; set; }
public AccountProfileViewModel() {
AP = new AccountProfile();
}
}
I think what you are trying to achieve is something like this:
public class AccountProfileViewModel
{
public AccountProfile AP { get; set; }
public AccountProfileViewModel() { }
}
or if AccountProfileViewModel really needs AccountProfile you can do
public class AccountProfileViewModel
{
public AccountProfile AP { get; set; }
public AccountProfileViewModel(AccountProfile profile) {
this.AP = profile;
}
}
and in your controller you can do something like this
public class controller {
public ActionResult Index(){
var vm = new AccountProfileViewModel();
var ap = //Get accountProfile
vm.AP = ap;
return View(vm);
}
}
or in the case of example where you need the AccountProfile
public class controller {
public ActionResult Index(){
var ap = //Get accountProfile
var vm = new AccountProfileViewModel(ap);
return View(vm);
}
}
you want AccountProfileViewModel to have an instance of the AccountProfile but you want to set it in the controller.
then in your view you can do Model.AP.AccountNumber for instance
If you need an object reference in this class then it's my personal preference to only create the object if it's required like so:
public class AccountProfileViewModel
{
private AccountProfile _ap;
public AccountProfile AP
{
get { return _ap ?? (_ap = new AccountProfile()); }
set { _ap = value; }
}
}
If you actually use yourObject.AP then it will have a reference created / return the existing one but if it's not used then no reference has been created.

implement repository in asp.net mvc 5

I got dbset for table Functions in database and FunctionsContext: dbContext. I am implementing repository. In my interface I have only one function at the movement "GetFunctions". I got stuck in implementing class; method "GetFunctions" where I need to call FunctionsContext to get all list of available functions title from database and then send to controller class
I am using mvc5 asp.net and entity framework
dbContext
public class FunctionsContext : dbContext
{
public DbSet<App_Functions> Functions { get; set; }
}
model
[Table("Functions")]
public class App_Functions
{
[Key]
public int Function_ID { get; set; }
[StringLength(50)]
[Required]
public string Title { get; set; }
public int Hierarchy_level { get; set; }
}
Domain Class
public class Functions
{
public Functions()
{
}
public int Function_ID { get; set; }
public string Title { get; set; }
public int Hierarchy_level { get; set; }
}
IRepository
interface IFunctionRepository: IDisposable
{
IQueryable<Functions> GetFunctions { get; }
}
IRepository Implementation class
public class FunctionRepository : IFunctionRepository
{
private FunctionsContext fun_Context = new FunctionsContext();
public IQueryable<Functions>GetFunctions
{
?????????
}
}
what I want to implement in IQueryableGetFunctions
using (var db = new FunctionsContext())
{
var query = from b in db.Functions
orderby b.Function_ID
select b;
foreach (var item in query)
{
var a2 = item.Title;
}
}
I think the easiest way will be the following:
public IQueryable<Functions> GetFunctions()
{
return fun_Context.Functions.Select(x=>new Functions {
Function_ID = x.Function_ID,
Title = x.Title,
Hierarchy_level = x.Hierarchy_level
});
}
You have to add () after the method name, this declaration does not work 'public IQueryable GetFunctions'
IRepository Implementation class
public class FunctionRepository : IFunctionRepository
{
private FunctionsContext fun_Context = new FunctionsContext();
// For method declaration add the () after the method name
public IQueryable<Functions> GetFunctions()
{
return fun_Context.Functions;
}
}

Resources