ASP.NET MVC, CRUD 2 tables 1 with foreign key - asp.net-mvc

I have 2 tables contract and account in my database, I want to modify the contract table only if the account code is in the account table.
The tables are created in the database already. I have 2 entities in my mvc application:
Contract entity:
public class Contract
{
[Key]
[HiddenInput(DisplayValue = false)]
public int ContractID { get; set; }
[Display(Name = "Account Code")]
//[ForeignKey("AccountCode")]
public string AccountCode { get; set; }
//public virtual Account AccountCode { get; set; }
[Display(Name = "Product Code")]
public string ProductCode { get; set; }
}
In my Accounts entity:
public class Accounts
{
[Key]
public string AccountCode { get; set; }
public string CompanyName { get; set; }
public string CompanyNumber { get; set; }
public string VATNumber { get; set; }
public string Telephone { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string PostCode { get; set; }
public string Country { get; set; }
//public virtual ICollection<Contract> Contract { get; set; }
}
The CRUD is working currently without the foreign keys as I have commented them out.
I have a foreign key (AccountCode)in the database on the contract table linking to the accounts table. How do I implement that on my mvc application with my entities above?
I have read google and tried the commentted code above without any success.
Thanks in advance for your help

This will do it for you
public class Contract
{
[Key]
[HiddenInput(DisplayValue = false)]
public int ContractID { get; set; }
public virtual Account Account{ get; set; }
[Display(Name = "Product Code")]
public string ProductCode { get; set; }
public string AccountAccountCode {get;set;}
//automatically treated as foreign key of Account[Notice ClassNameKey Format]
}

Related

Country and City Dropdown in ASP.NET Core MVC with db-first approach

I know this question might be asked so many times, I tried a lot to find the answer and ultimately I am throwing it here if some one can help me.
I am doing a project in ASP.NET Core MVC with a database-first approach. I have a registration form where I need to populate Country and City dropdowns to fill with data coming in through WeCareConext class.
In my controller I am doing this:
[HttpGet]
public IActionResult Register()
{
CompanyEditViewModel model = new CompanyEditViewModel();
var fromDatabaseEF = new SelectList(_context.Country.ToList(), "CountryId", "NameEn");
ViewData["CompanyRegister"] = fromDatabaseEF;
return View(model);
}
My Country model:
public partial class Country
{
public Country()
{
City = new HashSet<City>();
Currency = new HashSet<Currency>();
HolidayType = new HashSet<HolidayType>();
Holidays = new HashSet<Holidays>();
Province = new HashSet<Province>();
StaffInfo = new HashSet<StaffInfo>();
}
public int CountryId { get; set; }
public string NameAr { get; set; }
public string NameEn { get; set; }
public string NameFr { get; set; }
public string IsoCode2 { get; set; }
public string IsoCode3 { get; set; }
public string RegionAr { get; set; }
public string Region { get; set; }
public byte? PostcodeRequired { get; set; }
public bool? IsActive { get; set; }
public byte? IsAvailable { get; set; }
public string MobileMask { get; set; }
public byte? IsDeleted { get; set; }
public int? BaseCharges { get; set; }
public int? MobileNumberLength { get; set; }
public string CountryCode { get; set; }
public byte[] IconImage { get; set; }
public string PickerListAr { get; set; }
public string PickerListEn { get; set; }
public string PickerListFr { get; set; }
public virtual ICollection<City> City { get; set; }
public virtual ICollection<Currency> Currency { get; set; }
public virtual ICollection<HolidayType> HolidayType { get; set; }
public virtual ICollection<Holidays> Holidays { get; set; }
public virtual ICollection<Province> Province { get; set; }
public virtual ICollection<StaffInfo> StaffInfo { get; set; }
}
My CompanyEditViewModel class:
public class CompanyEditViewModel
{
[Display(Name = "Company Number")]
public string CompanyId { get; set; }
[Required]
[Display(Name = "Company Name")]
[StringLength(75)]
public string Name { get; set; }
[Required]
[Display(Name = "Country")]
public string CountryId { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
[Required]
[Display(Name = "City")]
public string SelectedCityCode { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
Unfortunately, this returns an error:
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
I am trying different approaches but not solving my issue. Can anyone suggest some code which can help me and I can also select country and then populate city dropdown according to the CountryID without page reload ? Thanks in advance.

Query and display in one view data coming from many to many with payload in Entity framework 6

I have this complex model:
public class Food
{
[Key]
public int FoodID { get; set; }
[Required]
[DisplayName("Food Name")]
public string FoodNameEN { get; set; }
[Required]
[DisplayName("Food Name")]
public string FoodNameFR { get; set; }
[Required]
[DisplayName("Food Name")]
public string FoodNameNL { get; set; }
[Required]
[DisplayName("Food Description")]
public string FoodDescriptionEN { get; set; }
[Required]
[DisplayName("Food Description")]
public string FoodDescriptionFR { get; set; }
[Required]
[DisplayName("Food Description")]
public string FoodDescriptionNL { get; set; }
public int CategoryID { get; set; }
[Required]
public bool Availability { get; set; }
[Required]
[DisplayName("Is Menu of the Day")]
public bool DailyMenu { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<FoodAttributeValue> FoodAttributeValues { get; set; } = new HashSet<FoodAttributeValue>();
public virtual ICollection<OrderDetail> OrderDetails { get; set; } = new HashSet<OrderDetail>();
public class Category
{
[Key]
public int CategoryID { get; set; }
[Required(ErrorMessage = "Please enter a Category Name for English")]
[DisplayName("Category Name")]
public string CategoryEN { get; set; }
[Required(ErrorMessage = "Please enter a Category Name for French")]
[DisplayName("Category Name")]
public string CategoryFR { get; set; }
[Required(ErrorMessage = "Please enter a Category Name for Dutch")]
[DisplayName("Category Name")]
public string CategoryNL { get; set; }
[Required]
public bool Availability { get; set; }
public virtual ICollection<Food> Foods { get; set; } = new HashSet<Food>();
}
public class Attribute
{
[Key]
public int AttributeID { get; set; }
public string AttributeNameEN { get; set; }
public string AttributeNameFR { get; set; }
public string AttributeNameNL { get; set; }
public virtual ICollection<AttributeValue> AttributeValues { get; set; } = new HashSet<AttributeValue>();
}
public class AttributeValue
{
[Key]
public int AttributeValueID { get; set; }
public int AttributeID { get; set; }
public string AttributeValueEN { get; set; }
public string AttributeValueFR { get; set; }
public string AttributeValueNL { get; set; }
public virtual Attribute Attribute { get; set; }
public virtual ICollection<FoodAttributeValue> FoodAttributeValues { get; set; } = new HashSet<FoodAttributeValue>();
}
public class FoodAttributeValue
{
[Key]
[Column(Order = 0), ForeignKey("Food")]
public int FoodID { get; set; }
[Key]
[Column(Order = 1), ForeignKey("AttributeValue")]
public int AttributeValueID { get; set; }
public decimal Price { get; set; }
public string CreatorUserName { get; set; }
public DateTime DateCreated { get; set; }
public virtual Food Food { get; set; }
public virtual AttributeValue AttributeValue { get; set; }
}
Attributes contains an attribute type like size or volume
AttributeValue contains the values for an attribute, like Normal Size, or Large.
FoodAttributeValue is a many to many table with payload "Price". So basically, the same Food comes in different sizes with different Prices.
My DatabaseContext:
public class ModelContext: DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Food> Foods { get; set; }
public DbSet<Attribute> Attributes { get; set; }
public DbSet<AttributeValue> AttributesValues { get; set; }
public DbSet<FoodAttributeValue> FoodAttributeValues { get; set; }
}
How can i query the model using linq, with the intention to have on the same view, the list of Foods that contain also the Attributes of the Food, the AttributeValues of it and eventually the Price?
Thanks in advance!
In MVC it is a best practice to create a ViewModel (or DTO) designed for the view you want to display. Generally, try to avoid using your entity POCOs in the view.
So for example:
public class FoodIndexViewModel
{
// Add the various entity fields you want here.
public int FoodID { get; set; }
...
// Take all these annotations out of your entity model. They belong here.
[Required]
[DisplayName("Food Name")]
public string FoodNameEN { get; set; }
...
[Required(ErrorMessage = "Please enter a Category Name for English")]
[DisplayName("Category Name")]
public string CategoryEN { get; set; }
public decimal Price { get; set; }
... etc. etc.
}
Now you can compose a LINQ query to populate the view model. AutoMapper can greatly ease this process.
var listOfFoodsVM = context.Foods
.Where(food => food.Availability)
.Select(food => new FoodIndexViewModel
{
FoodId = food.FoodId,
FoodNameEN = food.FoodNameEN,
... // other fields from food
CategoryEN = food.Category.CategoryEN,
// Here you would either pick a single value from the list based on your criteria
Price = food.FoodAttributeValues.FirstOrDefault(fav => fav.AttributeValueID == 1).Price
// or you could include a collection of FoodAttributes in your viewmodel:
FoodAtributes = food.FoodAttributes
... etc.
}).ToList();
Now you pass this into your view.
return View(listOfFoodsVM );

Ideal model structure for an ASP.NET MVC project for handeling multiple partial views

I have two partial views named as _centerDetails.cshtml and _centerRights.cshtml .
I am passing data from centerdetails when I click on submit and want to show this when another partial view is switched, but without posting it to the server.
This is my model class which I have created to handling my data via
controller:
namespace ADWP_AdminWebPortal.Models
{
public class CountryList
{
[Required(ErrorMessage = "Select a Country.")]
public int CountryId { get; set; }
[Required]
public string Country { get; set; }
[Required(ErrorMessage = "Select a State.")]
public int StateId { get; set; }
[Required]
public string State { get; set; }
[Required(ErrorMessage = "Select a City.")]
public int CityId { get; set; }
[Required]
public string City { get; set; }
}
public class CustomerDetails: CountryList
{
public int ClientId { get; set; }
[Required (ErrorMessage="Eneter the First name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Eneter the Middle name")]
[DataType(DataType.Text)]
public string MiddleName { get; set;}
public string NatureOfOccupation { get; set; }
public string AgentId { get; set; }
[Required(ErrorMessage ="Select a Client Type.")]
public string ClientType { get; set; }
public int TariffId { get; set; }
public string TariffName { get; set; }
public int ServiceId { get; set; }
public string ServiceName { get; set; }
public string OrderId { get; set; }
public int PaymentMethodId { get; set; }
public string PaymentMethodName { get; set; }
}
}
Here you can see the mess I have created. My problem is how to handle multiple models when you are working with multiple models in same controller?
Here I did not created all the data in a single class because I wanted it to reuse as per my need.
How can I handling data in a model? This is the main problem that is
coming to me while I am creating the partial views in my project.
You may use CTE and ROW_NUMBER function together to delete duplicate rows from your table.
With CTE AS (
SELECT VERIFICATIONTYPE,
NAME,
COST,
RN = ROW_NUMBER() OVER (PARTITION BY VERIFICATIONTYPE, NAME, COST ORDER BY VERFICATIONTYPE)
FROM DETAILS)
DELETE FROM CTE WHERE RN > 1
END
After a bit of a struggle I got the result.
public class CountryList
{
[Required(ErrorMessage = "Select a Country.")]
public int CountryId { get; set; }
[Required]
public string Country { get; set; }
}
// Added Class
public class State
{
[Required(ErrorMessage = "Select a State.")]
public int StateId { get; set; }
[Required]
public string State { get; set; }
}
// Added Class
public class City
{
[Required(ErrorMessage = "Select a City.")]
public int CityId { get; set; }
[Required]
public string City { get; set; }
}
public class CustomerDetails
{
public int ClientId { get; set; }
[Required (ErrorMessage="Enter the first name")]
[DataType(DataType.Text)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Enter the middle name")]
[DataType(DataType.Text)]
public string MiddleName { get; set; }
public int TariffId { get; set; }
public string TariffName { get; set; }
public int ServiceId { get; set; }
public string ServiceName { get; set; }
public string OrderId { get; set; }
public int PaymentMethodId { get; set; }
public string PaymentMethodName { get; set; }
public List<CountryList> { get; set; } //added list
public List<State> { get; set; } //added list
public List<City> { get; set; } //added list
}
Yeah, it was so easy.

MVC 4 Code First ForeignKeyAttribute on property ... on type ... is not valid

I keep getting this error and I do not know why.
The ForeignKeyAttribute on property 'Ward' on type 'BioSheet.Models.BioSheetModel' is not valid. The foreign key name 'WardId' was not found on the dependent type 'BioSheet.Models.BioSheetModel'. The Name value should be a comma separated list of foreign key property names.
public class Ward
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("AddressId")]
[Required]
public virtual Address WardAddress { get; set; }
[ForeignKey("BioSheetId")]
public virtual List<BioSheetModel> BioSheets { get; set; }
[Required]
public String Code { get; set; }
}
public class BioSheetModel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
public String Email { get; set; }
[ForeignKey("WardId")]
[Required]
public Ward Ward { get; set; }
public String CellPhoneNumber { get; set; }
public String HouseNumber { get; set; }
[Required]
public String DoB { get; set; }
[Required]
public Address Address { get; set; }
public String OtherInformation { get; set; }
public String PreviousCallings { get; set; }
[ForeignKey("TimePeriodId")]
public virtual TimePeriod TimePeriods { get; set; }
public String HomeWard { get; set; }
public Boolean OkToText { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public DateTime TodaysDate { get; set; }
[ForeignKey("EMPId")]
public virtual EDUEMP EduEmp { get; set; }
[ForeignKey("SingId")]
public virtual Sing Singing { get; set; }
[ForeignKey("MissionId")]
public virtual Mission MissionIn { get; set; }
}
Can anyone help me resolve this?
[ForeignKey("WardId")] indicates that the property to use as a foreign key to the Ward table should be the WardId property on the BioSheetModel class.
You're getting the error because you haven't defined a WardId property on the BioSheetModel class.
Add
public int WardId {get; set;}
for a non-nullable/required relationship, or
public int? WardId {get; set;}
for a nullable/optional relationship.

MVC Model Poco class, design issue,

i have a little issue.
I am trying to make a Address class were i save all my application's addresses.
The thing is that i want to be able to link several addresses to both customer and company.
Can someone please show me how i should design it?
I use MVC 4 with entityFramework code first.
public class Address
{
[Key]
public int AddressId { get; set; }
public string Street { get; set; }
public string Number { get; set; }
public string ZipCode { get; set; }
public int CountyId { get; set; }
public virtual County County { get; set; }
public int StateId { get; set; }
public virtual State State { get; set; }
public int CountryId { get; set; }
public virtual Country Country { get; set; }
}
public class Customer
{
[Key]
public int CustomerId { get; set; }
public int CompanyId { get; set; }
[Display(Name = "Kund")]
public string Name { get; set; }
public virtual Company Company { get; set; }
// wan't to display a ICollection of addresses.
//public virtual ICollection<Address> Addresses { get; set; }
}
public class Company
{
[Key]
public int CompanyId { get; set; }
[Display(Name = "Organisationsnummer")]
public string OrganisationNumber { get; set; }
[Display(Name = "Företag")]
public string Name { get; set; }
[Display(Name = "Företag skapat")]
public DateTime CreationDate { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
// wan't to display a ICollection of addresses.
//public virtual ICollection<Address> Addresses { get; set; }
}
At the following properties and annotations to your classes, it should help Entity Framework understand your relationships:
public class Address
{
[Key]
public int AddressId { get; set; }
public string Street { get; set; }
public string Number { get; set; }
public string ZipCode { get; set; }
public int CustomerId {get;set;}
[ForeignKey("CustomerId")]
public virtual Customer Customer {get;set;}
public int CompanyId {get;set;}
[ForeignKey("CompanyId")]
public virtual Company Company {get;set;}
public int CountyId { get; set; }
[ForeignKey("CountyId")]
public virtual County County { get; set; }
public int StateId { get; set; }
[ForeignKey("StateId")]
public virtual State State { get; set; }
public int CountryId { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
}
public class Customer
{
[Key]
public int CustomerId { get; set; }
public int CompanyId { get; set; }
[Display(Name = "Kund")]
public string Name { get; set; }
[ForeignKey("CompanyId")]
public virtual Company Company { get; set; }
[InverseProperty("Customer")]
public virtual ICollection<Address> Addresses { get; set; }
}
public class Company
{
[Key]
public int CompanyId { get; set; }
[Display(Name = "Organisationsnummer")]
public string OrganisationNumber { get; set; }
[Display(Name = "Företag")]
public string Name { get; set; }
[Display(Name = "Företag skapat")]
public DateTime CreationDate { get; set; }
[InverseProperty("Company")]
public virtual ICollection<Customer> Customers { get; set; }
[InverseProperty("Company")]
public virtual ICollection<Address> Addresses { get; set; }
[InverseProperty("Company")]
public virtual ICollection<Employee> Employees { get; set; }
}
public class Employee
{
[Key]
public int EmployeeId {get;set;}
public int CompanyId {get;set;}
[ForeignKey("CompanyId")]
public virtual Company Company {get;set;}
}
EDIT: You now have issue of another type. Your DELETE/UPDATE rules are causing the error you're seeing right now. You've most likely set CASCADE delete on multiple paths that lead to same primary key table. For start set all your relationships that look like this:
Then assume this scenario:
You have entities A, B and C.
Entity B has FK to entity A.
Entity C has FK to entity A and entity B.
You're allowed to set cascade delete/update only on one dependency path. This means that you can only do:
Cascade delete between A and B and cascade delete between B and C.
If you however add cascade delete between A and C as well along with above, you'll get an error you have now.

Resources