Join two model to present in a view in MVC - asp.net-mvc

I want to join two below model class with entity framework in controller for present factor in accounting system in a view
<pre>
namespace AccountingSystem.Models
{
public class BuyFactor
{
public int BuyFactorId { get; set; }
public DateTime CreateDate { get; set; }
public string Seller { get; set; }
public string Creator { get; set; }
public decimal SumAllPrice { get; set; }
public ICollection<BuyFactorDetail> BuyFactorDetails { get; set; }
}
}
namespace AccountingSystem.Models
{
public class BuyFactorDetail
{
public int BuyFactorDetailId { get; set; }
public int Number { get; set; }
public string Description { get; set; }
public decimal SumPrice { get; set; }
public int BuyFactorId { get; set; }
public virtual BuyFactor BuyFactor { get; set; }
public virtual Commodity Commodity { get; set; }
}
}
</pre>

Create a new Model
public class JointModel
{
public BuyFactor BuyFactor {get; set;}
public BuyFactorDetail BuyFactorDetail {get; set;}
}

Just create another model then calls the other model in there
public class ParentModel
{
public BuyFactor BuyFactor {get; set;}
public BuyFactorDetail BuyFactorDetail {get; set;}
}
So when you will call it in view
#model IEnumerable<AccountingSystem.Models.ParentModel>
#Html.DisplayNameFor(model => model.BuyFactor.Creator)

Best way define Model as a Property in Main Model
For example
public class BuyFactor
{
public int BuyFactorId { get; set; }
public DateTime CreateDate { get; set; }
public string Seller { get; set; }
public string Creator { get; set; }
public decimal SumAllPrice { get; set; }
public ICollection<BuyFactorDetail> BuyFactorDetails { get; set; }
public BuyFactorDetail BuyFactorEntity {get;set;}
}
Assign value in BuyFactorEntity and use as Model.BuyFactorEntity.BuyFactorDetailId

Use a Linq join query like
var query = (from b in context.BuyFactors
join d in context.BuyFactorDetail
on
..
select new
{
BuyFactorId = b.BuyFactorId,
....
BuyFactorDetailId = d.BuyFactorDetailId,
...
..
}));

Your BuyFactor already contains the BuyFactorDetail collection. You sure the entities are 1:N relationship with each other?
You can use the BuyFactor as model and could use the BuyFactorDetails propertu of the BuyFactor entity.

Use ViewBag in controller to assign respective objects for both.
ViewBag.BuyFactor= BuyFactor;
ViewBab.BuyFactorDetail = BuyFactorDetail;
To use it in view you will have to typecast them back.

Related

how to query against a many to many relation with entity framework 6

I have those 2 Models
public class BranchEmployees
{
public int ID { get; set; }
[Required, Column(Order = 0), Key]
public string ApplicationUserID { get; set; }
[Required, Column(Order = 1), Key]
public int BranchID { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }
public virtual ICollection<Branch> Branch { get; set; }
}
public class Branch
{
public int ID { get; set; }
public string BranchName { get; set; }
[Required]
public string ApplicationUserID { get; set; }
public ApplicationUser User { get; set; }
public virtual ICollection<BranchEmployees> BranchEmployees { get; set; }
}
public class ApplicationUser
{
//rest of the code
}
UPDATE
I have everything set up but what I want is the query that gets me the Employees whose IDs are in the branch employees table
, I'm using entity framework code first with MVC 5 , how do I do it ?
Assuming that your ApplicationUser class will have a navigational property called BranchEmployees, here is the query that gets me the Employees whose IDs are in the branch employees table
List<ApplicationUsers> employeeNames =
dbContext
.ApplicationUsers
.Where(au => au.BranchEmployees
.Count() > 0).ToList();
Also, can you provide whole model including ApplicationUser? I also wonder why you do not prefer BranchEmployees to inherit from ApplicationUser.
You don't need a class that indicates a many-to-many relation between two tables when you do code-first. The key here is to create virtual properties of those classes. Lets say you have a class Student and class Course. Students can be in many Courses and Courses can have many Students. To generate a database using these models the classes should look like this:
public class Student
{
private ICollection<Course> _courses;
public Student()
{
this._courses = new HashSet<Course>();
}
[Key]
public int Id { get; set; }
public string FullName { get; set; }
public virtual ICollection<Course> Courses
{
get { return this._courses; }
set { this._courses = value; }
}
}
And for Course:
public class Course
{
private ICollection<Student> _students;
public Course()
{
this._students = new HashSet<Student>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students
{
get { return this._students; }
set { this._students = value; }
}
}
I hope that this can help you solve your issue.

ASP.MET MVC Multiple Model in One View

I want to use multiple model in one view, I red some article to use complex Model, or Partial View, or Viewbag and other,but couldn't find normal answer.
I want to display data from different models.
Here is my Models
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public string Image { get; set; }
public IEnumerable<Teacher> Teachers { get; set; }
}
public class Teacher
{
public int TeacherID { get; set; }
public string TeacherName { get; set; }
public string TeacherLname { get; set; }
public int DepartmentID { get; set; }
public string Image { get; set; }
public Department Department { get; set; }
}
public class ClassOut
{
public int Id { get; set; }
public string ClassOutName { get; set; }
}
public class SchoolDbContext:DbContext
{
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<ClassOut> ClassOuts { get; set; }
}
Combine all your models in one common view model and use it in your view.
public class ViewModelName
{
public Department Department {get; set;}
public Teacher Teacher {get; set;}
public ClassOut ClassOut {get; set;}
}
Use this model for your view:
#model ViewModelName
......
#Html.TextBoxFor(x => x.Teacher.TeacherName )
.....
And in your post action method
public ActionResult MethodName(ViewModelName viewModel)
{
//
}
Try to create a Class ( for example Manager) where you add a variable for Department, ClassOut, ClassOutName and then you pass the Class Manager to the view and then you can access easily
public class Manager
{
public Department dept;
public ClassOut cl;
public ClassOutName clname;
}

Entity Framework 6 + One-To One

my Entities are as follows:
public partial class Employee :Person, IEntity<long>
{
.......
public long Salutation_Id { get; set; }
[Required]
[ForeignKey("Salutation_Id")]
public Salutation Salutation { get; set; }
}
public partial class Salutation:BaseEntity,IEntity<long>
{
public long Id { get; set; }
public string SalutationShort { get; set; }
public string SalutationLong { get; set; }
public string LetterSalutation { get; set; }
}
I'm looking for a way to convert this mapping to FluentAPI.
Any Ideas?
Something like...
modelBuilder.Entity<Employee>().HasRequired(e => e.Salutation).WithRequiredDependent().Map(ca => ca.MapKey(new string[] {"Salutation_Id"});
Of course, modelBuilder is an object of type DbModelBuilder, like what you would see when you override the OnModelCreating method of DbContext.

use two models in one view

net MVC 5 I have a view that require info from two models. In one modelView i have Student Marks and in the other, I have Student details How do I call both models to the view.
public class Student
{
[Key]
public int StudentNum { get; set; }
public string StudentName { get; set; }
public string StudentSurname { get; set; }
public string Email { get; set; }
}
public class Marks
{
[Key]
public int Mark1 { get; set; }
public int Mark2 { get; set; }
public int Dp { get; set; }
public int StudentNum { get; set; }
public virtual Student Student { get; set; }
}
Create a new View Model which encapsulates both the other view models as,
public class StudentViewModel
{
public Details Details { get; set; }
public Marks Marks { get; set; }
}
and pass it to the view you use. And access by Model.StudentViewModel.Details for getting student details and for marks Model.StudentViewModel.Marks.

Join two Models to display in webpage

I'm building an application using ASP.NET MVC4 with code first data migrations. I have an estimates model, a clients model, a DbContext, and a view model I created. I am wanting to display the company name in a drop down, with the company name tied to an estimate. I have a ClientId in both models. I also created a DbSet<> and that didn't work either when querying against it.
I tried to create a viewmodel that I thought I could simply query against and display through my controller. I'm not having any luck in getting this to work. After a day plus of looking on here and other places, I'm out of ideas.
How can I query/join the two models, or query the viewmodel to get the company name associated with the clientId? Thanks for the help.
Models:
public class Estimates
{
[Key]
public int EstimateId { get; set; }
public int ClientId { get; set; }
public decimal EstimateAmount { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime EstimateDate { get; set; }
public string EstimateNotes { get; set; }
}
public class Clients
{
[Key]
public int ClientId { get; set; }
public string CompanyName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public ICollection<Estimates> Estimates { get; set; }
public ICollection<Contracts> Contracts { get; set; }
}
public class ClientEstimateViewModel
{
public Clients Clients { get; set; }
public Estimates Estimates { get; set; }
}
public class NovaDb : DbContext
{
public NovaDb(): base("DefaultConnection")
{
}
public DbSet<Clients> Clients { get; set; }
public DbSet<Estimates> Estimates { get; set; }
public DbSet<Contracts> Contracts { get; set; }
public DbSet<Invoices> Invoices { get; set; }
public DbSet<ClientEstimateViewModel> ClientViewModels { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
Controller:
NovaDb _db = new NovaDb();
ClientEstimateViewModel ce = new ClientEstimateViewModel();
public ActionResult Index()
{
var model =
(from r in ce.Clients
join x in ce.Estimates
where
//var model =
// from r in _db.Clients
// orderby r.CompanyName ascending
// select r;
return View(model);
}
Because you've created the relationship between client & estimate in your models, you should be able to create a query like this:
var query = from c in _db.clients
select new ClientEstimateViewModel
{
Clients = c,
Estimates = c.Estimates
}
Although you'd have to change your model so Estimates was public List<Estimates> Estimates { get; set; }
This would give you a collection of ClientEstimateViewModel which you could then pass to your view

Resources