Complex Linq to Entities Query - linq

I have done simple LINQ queries but I am stumped on the 2 I need to create now. Basically I am going to get a class ID sent in. I will post the classes the entities are based on below.
public class ScheduledClass
{
public ScheduledClass()
{
Attendees = new List<ClassAttendee>();
}
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[HiddenInput(DisplayValue = false)]
[Required(ErrorMessage = "Please enter a topic")]
public int ClassTopicID { get; set; }
[Display(Name = "Topic")]
public virtual ClassTopic ClassTopic { get; set; }
[HiddenInput(DisplayValue = false)]
public int ClassTypeID { get; set; }
[Display(Name = "Class Type")]
public virtual ClassType ClassType { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Class Date")]
public DateTime ClassDate { get; set; }
[Display(Name = "Attendees")]
public virtual ICollection<ClassAttendee> Attendees { get; set; }
}
public ClassTopic()
{
Products = new List<ClassTopicProduct>();
}
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[Required(ErrorMessage = "Please enter a title")]
public string Title { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name = "Products")]
public virtual ICollection<ClassTopicProduct> Products { get; set; }
}
public class ClassTopicProduct
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[HiddenInput(DisplayValue = false)]
public int ClassTopicID { get; set; }
[ForeignKey("ClassTopicID")]
public ClassTopic ClassTopic { get; set; }
[HiddenInput(DisplayValue = false)]
public int ProductID { get; set; }
[ForeignKey("ProductID")]
public ProductType ProductType { get; set; }
}
public class CustomerEmail
{
public CustomerEmail()
{
CustomerEmailModules = new List<CustomerEmailModule>();
}
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[HiddenInput(DisplayValue = false)]
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
public string Name { get; set; }
public string Email { get; set; }
[DataType(DataType.PhoneNumber)]
public string PhoneNumber { get; set; }
[Display(Name = "Product Update")]
public Boolean SendProductUpdateEmail { get; set; }
[Display(Name = "Expiration ")]
public Boolean SendExpirationEmail { get; set; }
[Display(Name = "Products")]
public virtual ICollection<CustomerEmailModule> CustomerEmailModules { get; set; }
}
public class CustomerEmailModule
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[HiddenInput(DisplayValue = false)]
public int CustomerEmailID { get; set; }
public CustomerEmail CustomerEmail { get; set; }
[HiddenInput(DisplayValue = false)]
public int? ProductID { get; set; }
[ForeignKey("ProductID")]
public ProductType ProductType { get; set; }
}
EDIT___________________________
public class ProductType
{
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[Required(ErrorMessage = "Please enter a product type description")]
public string Description { get; set; }
public virtual ICollection<ProductTypeDetail> ProductDetails { get; set; }
}
EDIT_________________________________
So I am basically trying to send emails to people who might be interested in an upcoming class. Each class has a class topic. The class topic has 1 or more products associated with them. When I get the Class ID I need to go get all of the products associated with the class topic for the class. Once I have that I need to go look at CustomerEmails. Each CustomerEmail has any number of products that they are interested in associated with them. I need to find any CustomerEmail that has CustomerEmailModules where the PRoductID = Any of the product IDs in the Class Topic Products results. Here is what I tried to do below that is not working.
public JsonResult GetEmailClassInterest(int id)
{
var classprods = UoW.ScheduledClasses
.Where(o => o.ID == id)
.Select(p => new
{
p.ClassTopic.Products
});
var customeremails = from p in UoW.CustomerEmails where classprods.Any(z => z.Products.Any(x => x.ID == p.ID)) select p.Email;
return Json(customeremails, JsonRequestBehavior.AllowGet);
}
The query seems to run through ok but I get no results and there shoudl be base don the data I have. If anyone can tell me what I am doing wrong I would appreciate it.
Thanks

Try doing this:
var classprods = UoW.ScheduledClasses
.Where(o => o.ID == id)
.SelectMany(sched => sched.ClassTopic.Products.Select(prod => prod.ProductID));
var customerEmails = UoW.CustomerEmailModules.Include("CustomerEmails")
.Where(mod => mod.ProductID != null && classprods.Contains(mod.ProductID)
.Select(mod => mod.CustomerEmail.Email);

Related

Loading data from three related tables in ASP.NET Core using Entity Framwork Core in one-to-many relationship makes some data not displayed

I have three tables Customer, Loan and LoanHistories. Customer table is related to Loan table in a one-to-many relationship, and the Loan table is related to LoanHistories in one-to-many relationship as well.
The following are the C# classes for these tables:
public class Customer
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "ID NO")]
public int CustomerID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Phone Number")]
public string PhoneNo { get; set; }
[Display(Name = "Nearest Primary School")]
public string NearestPrimarySchool { get; set; }
[Display(Name = "Photo")]
public string Photo { get; set; }
public ICollection<Loan> loans { get; set; }
// public IEnumerable<LoansHistories> loansHistories { get; set; }
// public ICollection<WorkForLiving> workForLivings { get; set; }
// public ICollection<CustomersCharacterBehavior> customersCharacterBehaviors { get; set; }
}
public class Loan
{
[Key]
public int LoanID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal LoanAmount { get; set; }
[NotMapped]
public decimal TotalRepaidIn { get; set; }
[NotMapped]
public decimal Balance { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Loan Balance")]
private decimal _LoanBalance;
public decimal LoanBalance
{
get { return LoanAmount * interestRate; }
set { _LoanBalance = value; }
}
[Display(Name = "Interest Rate")]
public decimal interestRate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Application Date")]
public DateTime ApplicationDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Disbursement Date")]
public DateTime DisbursmentDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Due Date")]
public DateTime DueDate { get; set; }
[Display(Name = "Defaulted")]
public bool Defaulted { get; set; }
[Display(Name = "Approved")]
public bool Approved { get; set; }
//Navigation property
public int CustomerID { get; set; }
public Customer customer { get; set; }
//public ICollection<LoanComments> loancomments { get; set; }
public ICollection<LoansHistories> loansHistories { get; set; }
}
public class LoansHistories
{
[Key]
public int HistID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Repaid Amount")]
public decimal RePaidIn { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Repayement Date")]
public DateTime RepayementDateDate { get; set; }
[Display(Name = "No of paying interest only")]
public int NoOfPayinyingIntrestOnly { get; set; }
// Navigation properties
public int LoanID { get; set; }
public Loan loan { get; set; }
// Navigation property
// public int CustomerID { get; set; }
// public Customer customer { get; set; }
}
This is the LoansController that loads data from Loans and LoansHistories tables:
[HttpGet]
public async Task<ActionResult<IEnumerable<Loan>>> Getloans()
{
var data = await _context.loans
.Include(lh => lh.loansHistories)
.Select(l => new Loan()
{
TotalRepaidIn = l.loansHistories.Select(lh => lh.RePaidIn).Sum(),
Balance = l.loansHistories.Select(lh => lh.RePaidIn).Sum()-l.LoanAmount,
loansHistories = l.loansHistories,
ApplicationDate = l.ApplicationDate,
Defaulted = l.Defaulted,
DisbursmentDate = l.DisbursmentDate,
DueDate = l.DueDate,
LoanID = l.LoanID,
Approved = l.Approved,
interestRate = l.interestRate,
LoanAmount = l.LoanAmount
}).ToListAsync();
return data;
}
This is the data in JSON format:
[
{
"loanID":1,
"loanAmount":1000.0000,
"totalRepaidIn":202700.0000,
"balance":201700.0000,
"loanBalance":15000.000000,
"interestRate":15.00,
"applicationDate":"2022-03-28T00:00:00",
"disbursmentDate":"2022-03-28T00:00:00",
"dueDate":"2022-04-28T00:00:00",
"defaulted":false,
"approved":true,
"customerID":0,
"customer":null,
"loansHistories":[
{
"histID":1,
"rePaidIn":500.0000,
"repayementDateDate":"2022-03-28T00:00:00",
"noOfPayinyingIntrestOnly":1,
"loanID":1,
"loan":null
}
]
}
]
I want to load data from customer controller but I found entity TotalRepaidIn to be Zero, How can I make it return a value has its returning in loan controller? without having entity totalRepaidIn":0.0
Customer controller:
// GET: api/CustomersApi
[HttpGet]
public async Task<ActionResult<IEnumerable<Customer>>> Getcustomers()
{
return await _context.customers.Include(l=>l.loans).ThenInclude(h=>h.loansHistories).ToListAsync();
}
It returns the following Json data:
[
{
"customerID":30290122,
"firstName":"Isaac",
"lastName":"Kiplagat",
"phoneNo":"0724797768",
"nearestPrimarySchool":"Mokwo",
"photo":"photo",
"loans":[
{
"loanID":1,
"loanAmount":1000.0000,
"totalRepaidIn":0.0,
"balance":0.0,
"loanBalance":15000.000000,
"interestRate":15.00,
"applicationDate":"2022-03-28T00:00:00",
"disbursmentDate":"2022-03-28T00:00:00",
"dueDate":"2022-04-28T00:00:00",
"defaulted":false,
"approved":true,
"customerID":30290122,
"loansHistories":[
{
"histID":1,
"rePaidIn":500.0000,
"repayementDateDate":"2022-03-28T00:00:00",
"noOfPayinyingIntrestOnly":1,
"loanID":1
}
]
}
]
}
]
One way is like the previous did you can select the new Customer instance and set value for it one by one.
Another easier way, you can change your property to below to calculate the RePaidIn:
using System.Linq; //import this namespace...
public class Loan
{
[Key]
public int LoanID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal LoanAmount { get; set; }
private decimal _TotalRepaidIn;
[NotMapped]
public decimal TotalRepaidIn
{
get { return loansHistories.Sum(sum => sum.RePaidIn); }
set { _TotalRepaidIn = value; }
}
//other properties
public ICollection<LoansHistories> loansHistories { get; set; } = new List<LoansHistories>();
}
And in your LoansController, you can improve the action to below:
var data = await _context.loans.Include(lh => lh.loansHistories).ToListAsync();
Customer Controller can also get the correct value for TotalRepaidIn.

EF LINQ Query for selecting multiple table in single row and count

I have two tables with data for veterinary medicine.
Customers have many patients(pats), relation is "one to many".
I want to show customers with their petsname and count single line
Table: Customer
public class Customer
{
[Key]
public int ID { get; set; }
public bool IsActive { get; set; }
public string TC { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Note { get; set; }
public int AccountID { get; set; }
}
Table: Patient (Pet)
public class Patient
{
[Key]
public int PatientID { get; set; }
public bool IsActive { get; set; }
public int TypePatientID { get; set; }
public string TypeRace { get; set; }
public string CIPCode { get; set; }
public string Color { get; set; }
public string PatientName { get; set; }
public int Status { get; set; }
public int GenderID { get; set; }
public DateTime BirthDate { get; set; }
public DateTime? DeathDate { get; set; }
public int CustomerID { get; set; }
public int AccountID { get; set; }
}
public class CustomerPageModel
{
[Key]
public int ID { get; set; }
public bool IsActive { get; set; }
public string TC { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Note { get; set; }
public int AccountID { get; set; }
public string Pats { get; set; }
public int PatCount { get; set; }
}
I tried the following code:
var result = from p in context.Customers
join f in context.Patients on p.ID equals f.CustomerID
where p.AccountID == AccountID
group f by new { f.CustomerID, p.IsActive, p.TC, p.Name, p.Surname, p.Email, p.Address, p.Phone, p.Note, p.AccountID, f.PatientName,p.ID } into g
select new CustomerPageModel
{
ID=g.Key.ID,
IsActive = g.Key.IsActive,
TC = g.Key.TC,
Name = g.Key.Name,
Surname = g.Key.Surname,
Email = g.Key.Email,
Address = g.Key.Address,
Phone = g.Key.Phone,
Note = g.Key.Note,
AccountID = g.Key.AccountID,
Pats = string.Join(",", g.Select(x => x.PatientName))
};
Expected Result is:
[
{
"id":13,
"isActive":true,
"tc":"1234",
"name":"John ",
"surname":"Snow",
"email":"",
"address":"",
"phone":"",
"note":null,
"accountID":3,
"pats":"Oscar,Puffy",
"patCount":2
},
{
"id":14,
"isActive":true,
"tc":"2345",
"name":"Mark",
"surname":"Zurk",
"email":"",
"address":"",
"phone":"",
"note":null,
"accountID":3,
"pats":"Mars",
"patCount":1
}
]
Please check link:
https://dotnetfiddle.net/rsv45D
Can anyone help me to write this ef query?
Why Group by all the fields, as you just want to group by user that should be CustomerID (or whatever its key field is):
var result = from p in customers
join f in patients on p.ID equals f.CustomerID
where p.AccountID == AccountID
group new { f, p } by f.CustomerID into g
select new CustomerPageModel
{
ID = g.Key,
IsActive = g.First().p.IsActive,
TC = g.First().p.TC,
Name = g.First().p.Name,
Surname = g.First().p.Surname,
Email = g.First().p.Email,
Address = g.First().p.Address,
Phone = g.First().p.Phone,
Note = g.First().p.Note,
AccountID = g.First().f.AccountID,
Pats = string.Join(",", g.Select(x => x.f.PatientName)),
PatCount = g.Count()
};
Demo Link

Count total based on a foreign key value using LINQ

I'm trying to do something like the following done in SQL
SELECT COUNT(*) AS "Total"
FROM dbo.Items
WHERE CategoryID IN (SELECT CategoryID
FROM Categories
WHERE Name = 'Beverages')
Any ideas how we accomplish this in LINQ?
*Update
Item class code:
public class Item
{
[Key]
public int ItemID { get; set; }
public virtual Category Category { get; set; }
public virtual Brand Brand { get; set; }
public int CategoryID { get; set; }
public int BrandID { get; set; }
[Display(Name ="Product Name")]
[Required(ErrorMessage = "Product name is required")]
public string ItemName { get; set; }
[Display(Name="Product Price")]
public decimal? ItemPrice { get; set; }
[DataType(DataType.ImageUrl)]
[Display(Name = "Image URL")]
public string ImageUrl { get; set; }
}
Category class code:
public class Category
{
public int CategoryID { get; set; }
[DisplayName("Category Name")]
public virtual string Name { get; set; }
public virtual List<Item> Items { get; set; }
}
Update
Models
public class Item
{
[Key]
public int ItemID { get; set; }
public Category Category { get; set; }
public int CategoryID { get; set; }
public int BrandID { get; set; }
[Display(Name = "Product Name")]
[Required(ErrorMessage = "Product name is required")]
public string ItemName { get; set; }
[Display(Name = "Product Price")]
public decimal? ItemPrice { get; set; }
[DataType(DataType.ImageUrl)]
[Display(Name = "Image URL")]
public string ImageUrl { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public virtual string Name { get; set; }
public virtual List<Item> Items { get; set; }
}
Sample of data used
You want item's where category = Beverages
You can make it from items end
var itemsCount1 = dbcontext
.Items
.Count(x => x.Category.Name == "Beverages");
You can make it from categories end
//if there is no Category with the name Beverages return 0
var itemsCount2 = dbcontext
.Categories
.FirstOrDefault(x => x.Name == "Beverages")?.Items?.Count() ?? 0;
Query Result
You could get Count with following.
var results = Categories.Where(x=>x.Name.Equals("Beverages")
.Join(Items,
c=>c.CategoryID,
i=>i.CategoryID,
(c,i)=> i).Count();
For mock data,
var Categories = new List<Category>
{
new Category{CategoryID =1, Name ="Beverages"},
new Category{CategoryID =2, Name ="One"},
new Category{CategoryID =3, Name ="Two"}
};
var Items = new List<Item>
{
new Item{ItemID=3,CategoryID=4,ItemName="abc1"},
new Item{ItemID=1,CategoryID=1,ItemName="abc2"},
new Item{ItemID=1,CategoryID=1,ItemName="abc3"},
new Item{ItemID=1,CategoryID=1,ItemName="abc4"},
new Item{ItemID=1,CategoryID=1,ItemName="abc5"},
new Item{ItemID=2,CategoryID=1,ItemName="abc6"},
new Item{ItemID=3,CategoryID=4,ItemName="abc7"},
new Item{ItemID=4,CategoryID=2,ItemName="abc8"},
};
Output : 5
Update
var results = dbContext.Categories.Where(x=>x.Name.Equals("Beverages")
.Join(dbContext.Items,
c=>c.CategoryID,
i=>i.CategoryID,
(c,i)=> i).Count();

How to debug AutoMapper "Missing type map configuration or unsupported mapping" error

I have seen plenty of examples of this error occuring, for a wide variety of causes and I have gone through all the causes I can see, but still i get the error, so I am wondering if some one can give some information about what this error actually means, so i can try finding the cause. Here is some code:
Controller:
[HttpPost]
public ActionResult Edit(ProfileViewModel model)
{
if (ModelState.IsValid)
{
var person = new UserAttribute();
person = Mapper.Map<ProfileViewModel, UserAttribute>(model);
db.UserAttribute.Add(person);
db.SaveChanges();
}
View Model
public class ProfileViewModel
{
[Display(Name = "First Name")]
[StringLength(20)]
[Required]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[StringLength(30)]
[Required]
public string LastName { get; set; }
[Display(Name = "Gender")]
[Required]
public string Gender { get; set; }
[Display(Name = "Date of Birth")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DOB { get; set; }
[Display(Name = "Hair Color")]
public string HairColor { get; set; }
[Display(Name = "Eye Color")]
public string EyeColor { get; set; }
[Display(Name = "Body Type")]
public string Weight { get; set; }
[Display(Name = "Height")]
public string HeightFeet { get; set; }
public string HeightInches { get; set; }
public int UserId { get; set; }
public IEnumerable<SelectListItem> WeightList { get; set; }
public IEnumerable<SelectListItem> EyeColorList { get; set; }
public IEnumerable<SelectListItem> HairColorList { get; set; }
public IEnumerable<SelectListItem> HeightFeetList { get; set; }
public IEnumerable<SelectListItem> HeightInchesList { get; set; }
public IEnumerable<SelectListItem> GenderList { get; set; }
}
UserAttribute model:
public int ProfileId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public System.DateTime DOB { get; set; }
public string HairColor { get; set; }
public string EyeColor { get; set; }
public string HeightFeet { get; set; }
public string Weight { get; set; }
public int UserId { get; set; }
public string HeightInches { get; set; }
Mapping config:
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x => x.AddProfile<ViewToDomainMapProfile>());
Mapper.Initialize(x => x.AddProfile<DomainToViewMapProfile>());
}
}
public class ViewToDomainMapProfile : Profile
{
public override string ProfileName
{
get { return "ViewToDomainMapProfile"; }
}
protected override void Configure()
{
Mapper.CreateMap<ProfileViewModel, UserAttribute>()
.ForSourceMember(x => x.GenderList, y => y.Ignore())
.ForSourceMember(x => x.HairColorList, y => y.Ignore())
.ForSourceMember(x => x.EyeColorList, y => y.Ignore())
.ForSourceMember(x => x.WeightList, y => y.Ignore())
.ForSourceMember(x => x.HeightFeetList, y => y.Ignore())
.ForSourceMember(x => x.HeightInchesList, y => y.Ignore());
}
}
and the config is called in the global asax:
AutoMapperConfiguration.Configure();
Using Mapper.AssertConfigurationIsValid(); produces the following exception:
AutoMapper.AutoMapperConfigurationException :
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
==============================================================================================
ProfileViewModel -> UserAttribute (Destination member list)
----------------------------------------------------------------------------------------------
ProfileId
So, you need to add mapping for ProfileId.
Overall, it's a good practice to use Mapper.AssertConfigurationIsValid(); either in your unit tests (you have them, right?), or after your mapper configuration. It'll display detailed information for such a misconfigurations.
For the viewmodel => userattribute
I noticed that ProfileId is a destination property, but not a source property.
public int ProfileId { get; set; }
Do you need to add code to ingore this destination member?
Other:
I might also suggest using or customizing the automapper to map properties that present that match by name exclusively.
Also, when possible, please avoid model names ending in the word Attritribute as by convention this is used almost exclusively for actual attributes. (my apologies for nitpicking)

MVC 3 Dropdowns & Multiple Model ViewModel

I'm pretty new to MVC, but I'm trying to set up a two step user registration system. I have an register model and several other models in a viewmodel called Registration. A user will have a profile based on the register model and then they will select a Producer/Distributor/Restaurant/Importer that they are part of, or create a new one of those. My ViewModel that is returned doesn't validate or pickup the values in my dropdownlists. They populate correctly, but on the post they aren't in the vm. Below is my view/controller/and models. I've been searching the net for 2 days with no luck. Also, if you think my method of registration is wacky, let me know. Thanks!
controller:
public class RegistrationController : Controller
{
private vfContext db = new vfContext();
//
// GET: /Registration/
public ActionResult Register()
{
ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeID", "Name");
ViewBag.ProducerID = new SelectList(db.Producers, "ProducerID", "Name");
ViewBag.PublicationID = new SelectList(db.Publications, "PublicationID", "Name");
ViewBag.ImporterID = new SelectList(db.Importers, "ImporterID", "Name");
ViewBag.DistributorID = new SelectList(db.Distributors, "DistributorID", "Name");
ViewBag.RestaurantID = new SelectList(db.Restaurants, "RestaurantID", "Name");
RegistrationViewModel reg = new RegistrationViewModel();
ViewData.Model = reg;
return View("Registration");
}
[HttpPost]
public ActionResult Register(RegistrationViewModel vm)
{
if (ModelState.IsValid)
{
MembershipCreateStatus createStatus;
//email is userid
Membership.CreateUser(vm.Register.Email, vm.Register.Password, vm.Register.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
Profile current = Profile.GetProfile(vm.Register.Email);
current.FirstName = vm.Register.FirstName;
current.LastName = vm.Register.LastName;
current.Address1 = vm.Register.Address1;
current.Address2 = vm.Register.Address2;
current.City = vm.Register.City;
current.State = vm.Register.State;
current.Postal = vm.Register.Postal;
current.UserTypeID = vm.Register.UserTypeID;
view - i'm having a hard time copying it over, so the issue is with ddls, so here is how I have the user type id one done
#model vf2.Models.RegistrationViewModel
<div class="editor-label">
#Html.LabelFor(model => model.Register.UserTypeID, "User Type")
</div>
<div class="editor-field">
#Html.DropDownList("UserTypeID", String.Empty)
#Html.ValidationMessageFor(m => m.Register.UserTypeID)
</div>
Models:
public class RegistrationViewModel
{
public RegisterModel Register { get; set; }
public Producer Producer { get; set; }
public Distributor Distributor { get; set; }
//public Publication Publication { get; set; }
public Restaurant Restaurant { get; set; }
public Importer Importer { get; set; }
}
Here is my register model.
public class RegisterModel
{
//[Required]
//[Display(Name = "User name")]
//public string UserName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Address")]
public string Address1 { get; set; }
[Display(Name = "Address Cont.")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string Country { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
public int ProducerID { get; set; }
public int DistributorID { get; set; }
public int PublicationID { get; set; }
public int ImporterID { get; set; }
public int RestaurantID { get; set; }
public virtual Producer Producer{ get; set; }
public virtual Distributor Distributor { get; set; }
public virtual Publication Publication { get; set; }
public virtual Importer Importer { get; set; }
public virtual Restaurant Restaurant { get; set; }
[Required]
public int UserTypeID { get; set; }
public virtual UserType UserType { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
producer model:
public class Producer
{
public int ProducerID { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string Country { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public string Website { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public DateTime? UpdatedOn { get; set; }
public Boolean Active { get; set; }
public virtual ICollection<Wine> Wines { get; set; }
}
I think I figured this out by adding a the following to my viewmodel:
public IEnumerable<UserType> UserTypes { get; set; }
public IEnumerable<Producer> Producers { get; set; }
and then this to my view:
#Html.DropDownListFor(m=>m.Register.UserTypeID,new SelectList(Model.UserTypes,"UserTypeID","Name"),"Select account type")

Resources