EntityFramework6 ServerVersion return invalid operation - entity-framework-4

i use code first to build web application.
i have two main entity "Product and Category".a class for DbContext and class for DatabaseIntializer as below.
namespace WingtipToys.Models
{
public class Product
{
[ScaffoldColumn(false)]
public int ProductID { get; set; }
[Required, StringLength(100), Display(Name = "Name")]
public string ProductName { get; set; }
[Required, StringLength(10000), Display(Name = "Product Description"), DataType(DataType.MultilineText)]
public string Description { get; set; }
public string ImagePath { get; set; }
[Display(Name = "Price")]
public double? UnitPrice { get; set; }
public int? CategoryID { get; set; }
public virtual Category Category { get; set; }
}
}
==================================================
namespace WingtipToys.Models
{
public class Category
{
[ScaffoldColumn(false)]
public int CategoryID { get; set; }
[Required, StringLength(100), Display(Name = "Name")]
public string CategoryName { get; set; }
[Display(Name = "Product Description")]
public string Description { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
}
===========================================================
namespace WingtipToys.Models
{
public class ProductContext:DbContext
{
public ProductContext()
: base("WingtipToys")
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
}
=========================================================
namespace WingtipToys.Models
{
public class
ProductDatabaseInitializer:DropCreateDatabaseIfModelChanges<ProductContext>
{
protected override void Seed(ProductContext context)
{
GetCategories().ForEach(c => context.Categories.Add(c));
GetProducts().ForEach(p=>context.Products.Add(p));
}
private static List<Category> GetCategories()
{
var categories = new List<Category> {
new Category
{
CategoryID = 1,
CategoryName = "Cars"
},
new Category
{
CategoryID = 2,
CategoryName = "Planes"
},
new Category
{
CategoryID = 3,
CategoryName = "Trucks"
},
new Category
{
CategoryID = 4,
CategoryName = "Boats"
},
new Category
{
CategoryID = 5,
CategoryName = "Rockets"
},
};
return categories;
}
private static List<Product> GetProducts()
{
var products = new List<Product> {
new Product
{
ProductID = 1,
ProductName = "Convertible Car",
Description = "This convertible car is fast! The engine is powered by a neutrino based battery (not included)." +
"Power it up and let it go!",
ImagePath="carconvert.png",
UnitPrice = 22.50,
CategoryID = 1
},
new Product
{
ProductID = 2,
ProductName = "Old-time Car",
Description = "There's nothing old about this toy car, except it's looks. Compatible with other old toy cars.",
ImagePath="carearly.png",
UnitPrice = 15.95,
CategoryID = 1
},
new Product
{
ProductID = 3,
ProductName = "Fast Car",
Description = "Yes this car is fast, but it also floats in water.",
ImagePath="carfast.png",
UnitPrice = 32.99,
CategoryID = 1
},
new Product
{
ProductID = 4,
ProductName = "Super Fast Car",
Description = "Use this super fast car to entertain guests. Lights and doors work!",
ImagePath="carfaster.png",
UnitPrice = 8.95,
CategoryID = 1
},
new Product
{
ProductID = 5,
ProductName = "Old Style Racer",
Description = "This old style racer can fly (with user assistance). Gravity controls flight duration." +
"No batteries required.",
ImagePath="carracer.png",
UnitPrice = 34.95,
CategoryID = 1
},
new Product
{
ProductID = 6,
ProductName = "Ace Plane",
Description = "Authentic airplane toy. Features realistic color and details.",
ImagePath="planeace.png",
UnitPrice = 95.00,
CategoryID = 2
},
new Product
{
ProductID = 7,
ProductName = "Glider",
Description = "This fun glider is made from real balsa wood. Some assembly required.",
ImagePath="planeglider.png",
UnitPrice = 4.95,
CategoryID = 2
},
new Product
{
ProductID = 8,
ProductName = "Paper Plane",
Description = "This paper plane is like no other paper plane. Some folding required.",
ImagePath="planepaper.png",
UnitPrice = 2.95,
CategoryID = 2
},
new Product
{
ProductID = 9,
ProductName = "Propeller Plane",
Description = "Rubber band powered plane features two wheels.",
ImagePath="planeprop.png",
UnitPrice = 32.95,
CategoryID = 2
},
new Product
{
ProductID = 10,
ProductName = "Early Truck",
Description = "This toy truck has a real gas powered engine. Requires regular tune ups.",
ImagePath="truckearly.png",
UnitPrice = 15.00,
CategoryID = 3
},
new Product
{
ProductID = 11,
ProductName = "Fire Truck",
Description = "You will have endless fun with this one quarter sized fire truck.",
ImagePath="truckfire.png",
UnitPrice = 26.00,
CategoryID = 3
},
new Product
{
ProductID = 12,
ProductName = "Big Truck",
Description = "This fun toy truck can be used to tow other trucks that are not as big.",
ImagePath="truckbig.png",
UnitPrice = 29.00,
CategoryID = 3
},
new Product
{
ProductID = 13,
ProductName = "Big Ship",
Description = "Is it a boat or a ship. Let this floating vehicle decide by using its " +
"artifically intelligent computer brain!",
ImagePath="boatbig.png",
UnitPrice = 95.00,
CategoryID = 4
},
new Product
{
ProductID = 14,
ProductName = "Paper Boat",
Description = "Floating fun for all! This toy boat can be assembled in seconds. Floats for minutes!" +
"Some folding required.",
ImagePath="boatpaper.png",
UnitPrice = 4.95,
CategoryID = 4
},
new Product
{
ProductID = 15,
ProductName = "Sail Boat",
Description = "Put this fun toy sail boat in the water and let it go!",
ImagePath="boatsail.png",
UnitPrice = 42.95,
CategoryID = 4
},
new Product
{
ProductID = 16,
ProductName = "Rocket",
Description = "This fun rocket will travel up to a height of 200 feet.",
ImagePath="rocket.png",
UnitPrice = 122.95,
CategoryID = 5
}
};
return products;
}
}
}
here my connection string
<add name="WingtipToys"
connectionString="Data Source=hanaa-pc\hanaa;Initial Catalog=wingtiptoys;Integrated Security=True"
providerName="System.Data.SqlClient"/>
and i call databaseintializer in global.asax
namespace WingtipToys
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer(new ProductDatabaseInitializer());
}
}
}
in master file i use listview to get all categories from db:
public IQueryable<Category> GetCategories()
{
var _db = new ProductContext();
IQueryable<Category> query = _db.Categories;
return query;
}
when i run project with debugging at context class i got this from watch window:
i want to know why this always happen and how to fix it.
Thanks.

Related

Cannot insert explicit value for identity column in table 'tablename' when IDENTITY_INSERT is set to OFF

I am making an ASP application with mvc model and generated a db by my classes Now it try to fill the db with a DBInitializer.cs. It says that it cannot insert a value for identity column.
enter image description here
A class
public class Rider
{
public int RiderID { get; set; }
public String LastName { get; set; }
public String FirstName { get; set; }
public int CountryID { get; set; }
public int TeamID { get; set; }
public String Bike { get; set; }
public int Number { get; set; }
public Team Team { get; set; }
public Country Country { get; set; }
}
DBInitializer.cs
public static class DbInitializer
{
public static void Initialize(MotoContext context)
{
// Look for any countries.
if (context.Countries.Any())
{
return; // DB has been seeded
}
context.Countries.AddRange(
new Country { Name = "White Russia", CountryID = 189 },
new Country { Name = "Yemen", CountryID = 190 },
new Country { Name = "Zaire", CountryID = 191 },
new Country { Name = "Zambia", CountryID = 192 },
new Country { Name = "Zimbabwe", CountryID = 193 }
);
context.SaveChanges();
context.Teams.AddRange(
new Team { TeamID = 1, Name = "Avintia Racing", Logo = "Avintia.PNG" },
new Team { TeamID = 2, Name = "Cardion AB Motoracing", Logo = "AB.PNG" },
);
context.SaveChanges();
context.Races.AddRange(
new Race { Country = "Spain", Name = "Comunitat Valenciana", Description = "The Circuito de la Comunitat Valenciana was completed in 1999 and held rounds of the MotoGP and Spanish Motorcycle Championships in the same year. The Cheste track has several layouts, running anti-clockwise with varying lengths. MotoGP events are held on a 4km track comprising of five right handed corners, eight left handers and a 650m straight. Although the track is regarded as quite small, the pit complex contains 48 garages whilst the stadium style grandstands can seat up to 150,000 spectators. The circuit layout which allows all parts of the circuit to be seen from any stand helps to create a unique atmosphere enjoyed by Spanish and international riders alike and as the last race of the season there is always a party feeling to the Grand Prix, which was voted best GP of 2005 by IRTA.", Length = 4005, Date = DateTime.Parse("2017-06-09"), X = 649, Y = 363 }
);
context.SaveChanges();
context.Riders.AddRange(
new Rider { LastName = "Bradl", FirstName = "Stefan", CountryID = 62, TeamID = 4, Bike = "Honda", Number = 6 },
new Rider { LastName = "Pedrosa", FirstName = "Dani", CountryID = 159, TeamID = 5, Bike = "Honda", Number = 26 },
new Rider { LastName = "Marquez", FirstName = "Marc", CountryID = 159, TeamID = 5, Bike = "Honda", Number = 93 }
);
context.SaveChanges();
context.Tickets.AddRange(
new Ticket
{
Name = "Max Verstappen",
Email = "max#formule1.nl",
Address = "Amsterdam",
CountryID = 123,
RaceID = 1,
Number = 5,
OrderDate = DateTime.Parse("2017-01-24"),
Paid = false
},
new Ticket
{
Name = "Stef Wouters",
Email = "sw#ping.be",
Address = "Brussels",
CountryID = 15,
RaceID = 1,
Number = 3,
OrderDate = DateTime.Parse("2017-01-23"),
Paid = true
}
);
context.SaveChanges();
}
}
MotoContext.cs
public class MotoContext : DbContext
{
public MotoContext(DbContextOptions<MotoContext> options ) : base(options)
{
}
public DbSet<Team> Teams { get; set; }
public DbSet<Rider> Riders { get; set; }
public DbSet<Country> Countries { get; set; }
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Race> Races { get; set; }
protected override void OnModelCreating (ModelBuilder modelBuilder)
{
modelBuilder.Entity<Team>().ToTable("Team");
modelBuilder.Entity<Rider>().ToTable("Rider");
modelBuilder.Entity<Country>().ToTable("Country");
modelBuilder.Entity<Ticket>().ToTable("Ticket");
modelBuilder.Entity<Race>().ToTable("Race");
}
}
I see that you are specifying a TeamID value for each Team. Is that column an Identity column? If so, you cannot specify values for that column unless you enable the sql feature that let's you. The feature is called Identity_Insert.
Most likely, the solution is not to specify the value for TeamID.

How to bind Syncfusion MVC grid to a specific list property in my model

I can bind my grid to the whole model, here's an example of one working grid:
(Html.EJ().Grid<API_EventListDTO>("EventListGrid")
.Datasource(Model)
.Columns(col =>
{
col.Field("EventId").HeaderText("Event ID").TextAlign(TextAlign.Center).Width(75).Add();
col.Field("EventTypeDescription").HeaderText("Event Description").TextAlign(TextAlign.Center).Width(75).Add();
col.Field("CreatedOn").HeaderText("Created On").TextAlign(TextAlign.Center).Width(75).Add();
col.Field("Status").HeaderText("Status").TextAlign(TextAlign.Center).Width(75).Add();
col.Field("Message").HeaderText("Message").TextAlign(TextAlign.Center).Width(75).Add();
}))
Model in this case, is #model List<API_EventListDTO>.
However now I need to bind a new grid to a specific property of the model which is a list of items. How can I do that? What I need to write in #(Html.EJ().Grid<API_EventListDTO>("EventListGrid") and in .Datasource(Model)??
Thank you
I suspect that you need to bound the list as dataSource for the grid using Model. Please refer the below sample and code example.
Sample here
#model EJGrid.Controllers.HomeController.newclass
#(Html.EJ().Grid<Orders>("FlatGrid")
.Datasource(Model.empID)
.AllowPaging()
…..
)
[Controller.cs]
public class HomeController : Controller
{
public static List<Orders> order = new List<Orders>();
public static List<EmpID> emp = new List<EmpID>();
public ActionResult Index()
{
List<EmpID> emp1 = new List<EmpID>() { new EmpID() { ID = 1, Name = "Ewddada" }};
List<EmpID> emp2 = new List<EmpID>() { new EmpID() { ID = 2, Name = "Caxada" }};
List<EmpID> emp3 = new List<EmpID>() { new EmpID() { ID = 3, Name = "Nmbddj" }};
List<EmpID> emp4 = new List<EmpID>() { new EmpID() { ID = 4, Name = "Mbgfuydf" }};
List<EmpID> emp5 = new List<EmpID>() { new EmpID() { ID = 5, Name = "Nuhjbsd" }};
order.Add(new Orders( 1, "VINET", emp1, 32.38, new DateTime(2014, 12, 25), "Reims"));
order.Add(new Orders( 2, "TOMSP", emp2, 11.61, new DateTime(2014, 12, 21), "Munster"));
order.Add(new Orders( 3, "ANATER",emp3, 45.34, new DateTime(2014, 10, 18), "Berlin"));
order.Add(new Orders( 4, "ALFKI", emp4, 37.28, new DateTime(2014, 11, 23), "Mexico"));
order.Add(new Orders( 5, "FRGYE", emp5, 67.00, new DateTime(2014, 05, 05), "Colchester"));
newclass newModel = new newclass();
newModel.empID = emp1;
newModel.ord = order;
return View(newModel);
}
public class newclass {
public List<EmpID> empID { get; set; }
public List<Orders> ord { get; set; }
}
}
[Model class]
public class Orders
{
public Orders()
{
}
public Orders(int orderId, string customerId, List<EmpID> empId, double freight, DateTime orderDate, string shipCity)
{
this.OrderID = orderId;
this.CustomerID = customerId;
this.EmployeeID = empId;
this.Freight = freight;
this.OrderDate = orderDate;
this.ShipCity = shipCity;
}
public int? OrderID { get; set; }
public string CustomerID { get; set; }
public List<EmpID> EmployeeID { get; set; }
public double? Freight { get; set; }
public DateTime? OrderDate { get; set; }
public string ShipCity { get; set; }
}
public class EmpID
{
public int ID { get; set; }
public string Name { get; set; }
}
In the above code example Orders is the model which contains a property EMPID which is a list of items. In the controller page we have stored the list objects of the Orders and EMPID in a new class objects and passed it as a model. In this way the required list can be accessed using Model parameter in view page.

Checkboxes for attribute list

I am new to ASP.NET and web programming in global.
I'm trying to make web application for job applications. I've managed to save applicant name, mail etc. but now I'm having troubles with checkboxes. Every applicant should have Skills property which contains list of applicants skills (like Java, JavaScript etc.).
In my form there should be checkbox for every skill but I can't achieve that.
I have this so far:
My model:
public class Applicant
{
[Key]
public int ID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string Email { get; set; }
[DataType(DataType.MultilineText)]
public string Letter { get; set; }
[EnumDataType(typeof(Sex))]
public Sex Gender { get; set; }
[EnumDataType(typeof(Pos))]
public Pos Position { get; set; }
public enum Sex
{
[Display(Name = "Male")] Male = 1,
[Display(Name = "Female")] Female = 2
}
public enum Pos
{
[Display(Name = "Front-end")] Frontend = 1,
[Display(Name = "Back-end")] Backend = 2,
[Display(Name = "Tester")] Tester = 3,
[Display(Name = "System administrator")] SysAdmin = 4,
[Display(Name = "Project manager")] ProjMan = 5,
[Display(Name = "Database specialist")] Database = 6,
}
[Display(Name = "Candidate skills: ")]
public List<Skills> SkillList { get; set; }
public static List<Skills> getSkills()
{
List<Skills> skills = new List<Skills>()
{
new Skills() { ID = 1, skillName = "Java", isChecked = false },
new Skills() { ID = 2, skillName = "JavaScript", isChecked = false },
new Skills() { ID = 3, skillName = "PHP", isChecked = false },
};
return skills;
}
}
public class Skills
{
[Key]
public int ID { get; set; }
public string skillName { get; set; }
public bool isChecked { get; set; }
}
In controller I get error
" Cannot implicitly convert type
'System.Collections.Generic.List jobAppForm.Models.Skills ' to
'System.Collections.Generic.List jobAppForm.Models.Applicant ' "
My controller:
// GET
public ActionResult Create()
{
List<Applicant> model = new List<Applicant>();
model = Applicant.getSkills();
return View(model);
}
So I have Create view which contains textboxes for FName, LName.... and dropdownlist for Gender and Position.
What I can't figure out is how to display checkboxes for every skill and save data to database.
Assuming your Skill class contains a name and a boolean property, and assuming you are using Razor for your view, you create a list of checkbox form fields all with a common "name" property but each one includes an index such as name="myname[0]". When you post the form your controller gets an array of values for "myname" you iterate through.
#for (int i = 0; i < Model.SkillList.Count(); i++)
{
string checkedValue = "false";
#if (Model.SkillList[i])
{
checkedValue = "checked";
}
#Html.CheckBox("myname[" + i.ToString() + "]", new { #checked = checkedValue })
}
Note: when you process the posted values an unchecked box value will be "false" and a checked box will be "true, false" so be careful to interpret the value as myname[i] != "false".
Try:
#for(int i = 0;i < Model.SkillList.Count;i++)
{
#Html.CheckBoxFor(model => model.SkillList[i].IsSelected)
#Html.DisplayFor(model => model.SkillList[i].skillName)
}

Cannot implicitly convert type 'int?' to 'System.Collections.Generic.List<Model>

I am new to MVC and LINQ.
I am trying to provide a model to a view using LINQ.
This model is comprised of a list of another model.
This is the first model.
public class MasterCategoryModel
{
[Key]
public int CategoryId { get; set; }
[Required(ErrorMessage = "Category name is mandatory")]
[StringLength(255, ErrorMessage = "Category name cannot exceed 255 characters")]
[Display(Name = "Category name ")]
public string Name {get;set;}
[StringLength(1000, ErrorMessage = "Category description cannot exceed 1000 characters")]
[Display(Name = "Category description")]
public string Description{get;set;}
}
This is the more problematic model:
public class CategoryModel
{
[Key]
public int CategoryId { get; set; }
[Required]
[StringLength(255, ErrorMessage = "Category name cannot exceed 255 characters")]
[Display(Name = "Category nam")]
public string Name { get; set; }
[StringLength(1000, ErrorMessage = "Category description cannot exceed 1000 characters")]
[Display(Name = "Category description")]
public string Description { get; set; }
[Required]
public List<MasterCategoryModel> MasterCategory { get; set; }
}
In my controller I currently have the following:
[Authorize(Users = "Administrator")]
[HttpGet]
public PartialViewResult _SubCategory()
{
using (var db = new TSCEntities())
{
var query = from p in db.Categories
where p.ParentCategoryId != null
select new CategoryModel()
{
CategoryId = p.CategoryId,
Name = p.Name,
Description = p.Description,
MasterCategory = p.ParentCategoryId
};
return PartialView(query.ToList());
}
}
MasterCategory = p.ParentCategoryId fails.
Can anyone help with a LINQ expression which would somehow give a List?
Database table code:
CREATE TABLE [product].[Categories](
[CategoryId] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](255) NOT NULL,
[Description] [nvarchar](1000) NULL,
[ParentCategoryId] [int] NULL,
PRIMARY KEY CLUSTERED
(
[CategoryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [product].[Categories] WITH CHECK ADD CONSTRAINT [FK_Category_ParentCategory] FOREIGN KEY([ParentCategoryId])
REFERENCES [product].[Categories] ([CategoryId])
GO
ALTER TABLE [product].[Categories] CHECK CONSTRAINT [FK_Category_ParentCategory]
GO
This is the class generated by EF.
public partial class Category
{
public Category()
{
this.Categories1 = new HashSet<Category>();
}
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> ParentCategoryId { get; set; }
public virtual ICollection<Category> Categories1 { get; set; }
public virtual Category Category1 { get; set; }
}
According your code, MasterCategory is a List, and you need to get it by id from your database. List can be created using the constructor with IEnumerable as a parameter:
var query = from p in db.Categories
where p.ParentCategoryId != null
select new CategoryModel()
{
CategoryId = p.CategoryId,
Name = p.Name,
Description = p.Description,
MasterCategory = new List<MasterCategoryModel>((from c in db.Categories where c.CategoryId == p.ParentCategoryId select c).AsEnumerable())
};
Update
I think that not all the Linq Extension methods are available because of lack of the using directive:
using System.Linq;
Answer came after reading this post .
This bit worked.
var query = from p in db.Categories
where p.ParentCategoryId != null
select new CategoryModel()
{
CategoryId = p.CategoryId,
Name = p.Name,
Description = p.Description,
MasterCategory = new List<MasterCategoryModel>((from c in db.Categories where c.CategoryId == p.ParentCategoryId select new MasterCategoryModel { CategoryId = c.CategoryId, Name = c.Name, Description = c.Description}).AsEnumerable().ToList())
};
Many thanks to you all, specially #Ehsan Sajjad and #VMAtm.
You have to join the tables like this:
var query = from p in db.Categories
join c in db.Categories on p.ParentCategoryId equals c.CategoryId
where p.ParentCategoryId != null
select new CategoryModel()
{
CategoryId = p.CategoryId,
Name = p.Name,
Description = p.Description,
MasterCategory = c.ToList().Select(x=>
new MasterCategoryModel
{
CategoryId= x.CategoryId,
Name = x.Name,
Description = x.Description
}).ToList()
};

how to get data from multiple related tables and pass it to the view mvc

i have three table in my data base category and Subcategory and product:
category has many Subcategory
Subcategory has many product
so i'm trying to join this three table to get the data for each product and display it in a view like that:
public ActionResult Index()
{
var memberId = WebSecurity.CurrentUserId;
var productsCompany = db.Products
.Join(db.SubCategorys, p => p.SubCategoryID, subcat => subcat.SubCategoryID,
(p, subcat) => new { p = p, subcat = subcat })
.Join(db.Categorys, temp0 => temp0.subcat.CategoryID, cat => cat.CategoryID,
(temp0, cat) => new { temp0 = temp0, cat = cat })
.Join(db.Sizes, temp1 => temp1.temp0.p.SizeID, s => s.SizeID,
(temp1, s) => new { temp1 = temp1, s = s })
.Join(db.Colors, temp2 => temp2.temp1.temp0.p.ColorID, c => c.ColorID,
(temp2, c) => new { temp2 = temp2, c = c })
.Join(db.Stores, temp3 => temp3.temp2.temp1.temp0.p.StoreID, st => st.StoreID,
(temp3, st) => new { temp3 = temp3, st = st })
.Join(db.Companyies, temp4 => temp4.st.CompanyID, camp => camp.CompanyID,
(temp4, camp) => new { temp4 = temp4, camp = camp })
.Where(temp5 => (temp5.camp.UserID == memberId))
.Select(temp5 => new
{
CategoryName = temp5.temp4.temp3.temp2.temp1.cat.CategoryName,
SubCategoryName = temp5.temp4.temp3.temp2.temp1.temp0.subcat.SubCategoryName,
ProductImageURL = temp5.temp4.temp3.temp2.temp1.temp0.p.ProductImageURL,
ProductName = temp5.temp4.temp3.temp2.temp1.temp0.p.ProductName,
Price = temp5.temp4.temp3.temp2.temp1.temp0.p.Price,
SizeName = temp5.temp4.temp3.temp2.s.SizeName,
ColorName = temp5.temp4.temp3.c.ColorName,
Quantity = temp5.temp4.temp3.temp2.temp1.temp0.p.Quantity,
Sales = temp5.temp4.temp3.temp2.temp1.temp0.p.Sales,
Discount = temp5.temp4.temp3.temp2.temp1.temp0.p.Discount,
StoreName = temp5.temp4.st.StoreName,
CompanyName = temp5.camp.CompanyName
}).ToList();
return View(productsCompany);
}
but in this way it take time to get the data so i' trying another way like that:
public ActionResult Index()
{
var memberId = WebSecurity.CurrentUserId;
var productsCompany = db.Products.Include(p => p.Color).Include(p => p.Size).Include(p => p.Store).Include(p => p.SubCategory);
return View(productsCompany.ToList());
}
but i cant figure out how can i get the data from the threed table category in this way and this only for display the data in this index view any idea on how can i create a new product from this three tables and thanks for any help
Update my classes is:
Product class
public class Product
{
[ScaffoldColumn(false)]
public int ProductID { get; set; }
[DisplayName("Image URL")]
//[DataType(DataType.Url)]
public string ProductImageURL { get; set; }
[Required(ErrorMessage = "Product Name is required")]
[DisplayName("Product Name")]
[StringLength(40)]
public string ProductName { get; set; }
[Required(ErrorMessage = "Price is required")]
[DisplayName("Product Price")]
[DataType(DataType.Currency)]
[Range(1, 5000.00, ErrorMessage = "Price must be between 1 SP and 5000.00 SP")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Quantity is required")]
[DisplayName("Product Quantity")]
public int Quantity { get; set; }
[DisplayName("Sales Amount")]
[Range(0, 100, ErrorMessage = "sale Prsent must be between 1 and 100")]
public int Sales { get; set; }
//Exclude
public decimal Discount { get; set; }
[Required(ErrorMessage = "Color is required")]
[DisplayName("Color")]
public int ColorID { get; set; }
public virtual Color Color { get; set; }
[Required(ErrorMessage = "Size is required")]
[DisplayName("Size Type")]
public int SizeID { get; set; }
public virtual Size Size { get; set; }
[Required(ErrorMessage = "Store is required")]
[DisplayName("Store")]
public int StoreID { get; set; }
public virtual Store Store { get; set; }
[Required(ErrorMessage = "Category Type is required")]
[DisplayName("Sub Category Type")]
public int SubCategoryID { get; set; }
public virtual SubCategory SubCategory { get; set; }
}
Subcategory class:
public class SubCategory
{
[ScaffoldColumn(false)]
public int SubCategoryID { get; set; }
[Required(ErrorMessage = "Category Type is required")]
[DisplayName("Category Type")]
[StringLength(40)]
public string SubCategoryName { get; set; }
[Required(ErrorMessage = "Category is required")]
[DisplayName("Category")]
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Category class:
public class Category
{
[ScaffoldColumn(false)]
public int CategoryID { get; set; }
[Required(ErrorMessage = "Category Name is required")]
[DisplayName("Category Name")]
[StringLength(50)]
public string CategoryName { get; set; }
public virtual ICollection<SubCategory> SubCategorys { get; set; }
}
Assuming that your category, sub category and product table are relate with forign key
If you are using Entity Framework to access the data from database and ProxyCreationEnabled is set to true (by default it is true) in your dbContext class constructor, The product table will automatically retrieve the related category and subcategory data for the specific product.
For example:
Product objProduct = _datacontext.Product.where(p=> p.productId.equals(pid));
and your Product table is defined as below:
public class Product
{
public int productId {get; set;}
...
public virtual IEnumarable<Category> pCategories {get; set;}
public virtual IEnumarable<SubCategory> pSubCategories {get; set;}
}
so now your objProduct will automatically store the related Category and SubCategory in pCategories and pSubCategories respectively. you can access it directly, No need to Join or Inclue the related tables explicitly.
Now pass the object to the view as a Model
public ActionResult Index()
{
Product objProduct = _datacontext.Product.SingleOrDefault(p=> p.productId.equals(pid));
return View(objProduct);
}
and use the Model in the view as per requirement.

Resources