I'm new in Asp.Net and Entity Framework and i have a little issue.
I know u can help me , because its simple and i only know how to do it in PHP XD
I Have 2 models
public class Suppliers
{
public int ID { get; set; }
public int ID_Guard { get; set; }
public string Supplier{ get; set; }
public string Description { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm tt}", ApplyFormatInEditMode = true)]
public DateTime Enter { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm tt}", ApplyFormatInEditMode = true)]
public DateTime Exit { get; set; }
public virtual Guard Guard { get; set; }
}
public class Guard
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Suppliers> Suppliers{ get; set; }
}
controller
public class SuppliersController : Controller
{
private SuppliersContext db = new SuppliersContext();
public ActionResult Index()
{
return View(db.Suppliers.ToList());
}
}
And i wanna pass to the view the 2 table data and relate it
When i go to index show me all the suppliers data and show the Guard name( the person who registered the supplier enter and exit)
Well its solved
var results = from c in db.Suppliers
join cn in db.Guard on c.ID_Guard equals cn.ID
where (c.ID_Guard == cn.ID)
select new Models.MyViewModel{ Name= cn.Name, ID = c.ID, Supplier=c.Supplier, Description=c.Description, Enter=c.Enter, Exit=c.Exit};
follow the below code it works and seems same like yours also i added the link hope you find It helpful
public class Product
{
public Product() { Id = Guid.NewGuid(); }
public Guid Id { get; set; }
public string ProductName { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
}
public class ProductCategory
{
public int Id { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
/////view model///
public class ProductViewModel
{
public Guid Id { get; set; }
[Required(ErrorMessage = "required")]
public string ProductName { get; set; }
public int SelectedValue { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
[DisplayName("Product Category")]
public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}
follow the below tutorial
relationship model
for basic join use below query
var dealercontacts = from contact in table1
join table2 in table2 on contact.Id equals another.ID
select contact;
Related
I want to write a query for the API to get all desired data as JSON while keeping all related tables in the final result. I studied this thread but I could not implement it in my case. I have the following model:
Equipment.cs
public class Equipment
{
[Key]
public long EquipmentId { get; set; }
[Required]
public string EquipmentCode { get; set; }
[Required]
public string EquipmentTitle { get; set; }
[Required]
public bool IsActive { get; set; }
//Navigation properties
[Required]
public int CostCenterId { get; set; }
public CostCenter CostCenter { get; set; }
public int? EquipmentCategoryId { get; set; }
public EquipmentCategory? EquipmentCategory { get; set; }
public int EquipmentTypeId { get; set; }
public EquipmentType equipmentType { get; set; }
}
CostCenter.cs
public class CostCenter
{
[Key]
public int CostCenterId { get; set; }
[Required]
[MaxLength(100)]
public string Title { get; set; }
[Required]
public bool IsActive { get; set; } = true;
//Navigation properties
[JsonIgnore]
public virtual List<Equipment>? Equipments { get; set; }
}
EquipmentCategory.cs
public class EquipmentCategory
{
[Key]
public int EquipmentCategoryId { get; set; }
[Required]
[MaxLength(100)]
public string CategoryCode { get; set; }
[Required]
[MaxLength(100)]
public string CategoryName { get; set; }
//Navigation property
[JsonIgnore]
public virtual List<Equipment>? Equipments { get; set; }
}
EquipmentType.cs
public class EquipmentType
{
[Key]
public int EquipmentTypeId { get; set; }
[Required]
[MaxLength(100)]
public string EquipmentTypeTitle { get; set; }
//Navigation property
[JsonIgnore]
public virtual List<Equipment>? Equipments { get; set; }
}
I use the following codes in the controller:
var query = "SELECT * FROM Equipments INNER JOIN CostCenters ON CostCenters.CostCenterId = Equipments.CostCenterId WHERE EquipmentCode LIKE '1101%'"
var result = connection.Query<Equipment>(query).ToList();
return Ok(result);
First you need to join all tables and then map the relations to Equipment object like this:
var query = #"
SELECT * FROM Equipments INNER JOIN CostCenters ON CostCenters.CostCenterId = Equipments.CostCenterId
INNER JOIN EquipmentCategories ec ON Equipments.EquipmentCategoryId = ec.EquipmentCategoryId
INNER JOIN EquipmentTypes t ON Equipments.EquipmentTypeId = t.EquipmentTypeId
WHERE EquipmentCode LIKE '1101%'";
var result = connection.Query<Equipment,CostCenter,EquipmentCategory,EquipmentType, Equipment>
(query,(equipment, center, category, type)=>{
equipment.CostCenter=center;
equipment.EquipmentCategory=category;
equipment.EquipmentType=type;
return equipment;
}).ToList();
return Ok(result);
I am using EntityFramework which creates a local database and I would like to perform Join operation to show the Purchases done for each Customer, but I can't see to make it work.
Here is my Customer Model
public class Customer
{
[Key]
public int custId { get; set; }
public string firstName { get; set; }
public string surname { get; set; }
public string addresss { get; set; }
}
Here is my Purchase Model
public class Purchase
{
public int purchaseId { get; set; }
public int custId { get; set; }
public int productId { get; set; }
public double price { get; set; }
public int quantity { get; set; }
public double deliveryFees { get; set; }
public double finalAmount { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime dateOfPurchase { get; set; }
}
I have tried to create a ViewModel which should keep each Model in the class, so that I could perform join and it is shown down below:
public class ViewModel
{
public Customer customer { get; set; }
public Purchase purchase { get; set; }
public List<Customer> customers;
public List<Purchase> purchases;
}
And I have created a Controller for ViewModel to try to
public ActionResult Index()
{
using (db)
{
var cust = (from p in db.PurchaseList
join c in db.Customers on p.custId equals c.custId
select new
{
id = p.custId,
firstName = c.firstName,
surname = c.surname,
total = p.finalAmount.ToString()
}
).ToList();
return View(cust);
}
}
The db variable is the context of the database that I am using.
public Context() : base("name=Context")
{
}
public void CreateDatabase()
{
}
public System.Data.Entity.DbSet<Models.Offer> Offers { get; set; }
public System.Data.Entity.DbSet<Models.Employee> Employees { get; set; }
public System.Data.Entity.DbSet<Models.Customer> Customers { get; set; }
public System.Data.Entity.DbSet<Models.User> Users { get; set; }
public System.Data.Entity.DbSet<Models.Purchase> PurchaseList { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
In my View page I am only doing a foreach to retrieve the data but it is always empty. Do you have any suggestion? Should I use a different approach to the above?
Have you given correct relationships in your dbContext class?
Refer my sample application
(https://github.com/AvanthaSiriwardana/TheProjector-V1.0/blob/master/TheProjector.Domain/Entities/TheProjectorContext.cs)
Tried to separate my customer management playground solution into modules with following logics:
A Customer might have Orders.
An Order has OrderDetails which might correspond to InvoiceDetails which should be part of an Invoice.
Order is part of CustomerManagement project and Invoice is in separate project which is referenced in CustomerManagement.
I have defined two dbcontexts one for CustomerManagement and other one for invoice management, the later derives from the first one, that should allow me to use the entities defined in CustomerManagement when dealing with invoices, f.e. the following silly navigation Invoice.InvoiceDetails.First().OrderDetail.Order.Customer.
CustomerManagement model defines customer, his phones and other data;
Invoice management model defines invoice, invoice details and inherits orders to add a new navigation property between OrderDetail and InvoiceDetail, now since EF6 doesn't like the use of the same simple named types in one model I had to call the extending type FI_OrderDetail. Here I want to be able to navigate like this db.OrderDetails.First(od => od.Id == id).InvoiceDetail. Now, I want to prevent awkward searches like db.InvoiceDetails.First(invd => invd.OrderDetail.Id == id)
And here arises the first question, since I don't add any real data I want to use the same table, but EF will seek for a discriminator, but there is no need for it since effectively it is the same entity, what should I do? I can use Ignore<T> of DbModelBuilder, but then all other entities that use that ignored type for navigation purposes won't find it. Is there some other approach I should use or I miss something in my scenario?
Below are sample models:
namespace CustomerManagement
{
public partial class Customer
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Given Name")]
public string GivenName { get; set; }
[Required]
[Display(Name = "Surname")]
public string Surname { get; set; }
public virtual ICollection<Order> Orders { get; set; }
public virtual IList<Phone> Phones { get; set; }
}
public class Order
{
[Key]
[Column("Id", TypeName = "int")]
public int Id { get; set; }
public string CustomerId { get; set; }
[Required]
[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm}", ApplyFormatInEditMode = true)]
public DateTime? Date { get; set; }
public string Notes { get; set; }
[InverseProperty("Orders")]
public virtual Customer Customer { get; set; }
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
public class OrderDetail
{
[Key]
public int Id { get; set; }
[Required]
public int OrderId { get; set; }
[Required]
public decimal Price { get; set; }
[Required]
public string Description { get; set; }
[ForeignKey("OrderId")]
public virtual Order Order { get; set; }
}
public class CMDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Phone> Phones { get; set; }
}
}
namespace Finance
{
public class Invoice
{
[Key]
[Column("Id", TypeName = "int")]
public int Id { get; set; }
[Display(Name = "Customer ID")]
public int CustomerId { get; set; }
[Required]
[Display(Name = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
[ForeignKey("CustomerId")]
public virtual CustomerManagement.Customer Customer { get; set; }
public virtual ICollection<InvoiceDetail> InvoiceDetails { get; set; }
}
public class InvoiceDetail
{
[Key]
[Column("Id", TypeName = "int")]
public int Id { get; set; }
[Required]
public int InvoiceId { get; set; }
public string Details { get; set; }
public decimal Price { get; set; }
[ForeignKey("InvoiceId")]
public virtual Invoice Invoice { get; set; }
public virtual FI_OrderDetail OrderDetail { get; set; }
}
public class FI_OrderDetail : CustomerManagement.OrderDetail
{
public virtual ICollection<InvoiceDetail> InvoiceDetails { get; set; }
}
public class FIDbContext : CustomerManagement.CMDbContext
{
public new DbSet<FI_OrderDetail> OrderDetails { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<InvoiceDetail> InvoiceDetails { get; set; }
}
}
I've been trying to get something done in .NET EF for some time now.
My model looks like this:
public class Route
{
[Key]
public int RouteId { get; set; }
[Display(Name = "Rope")]
public int ropeId { get; set; }
public virtual Rope rope { get; set; }
[Display(Name = "Routesetter")]
public int routeSetterId { get; set; }
public virtual RouteSetter routeSetter { get; set; }
[Display(Name = "Secundary routesetter")]
public int? secundaryRouteSetterId { get; set; }
public virtual RouteSetter secundaryRouteSetter { get; set; }
[Display(Name = "Grade")]
public int gradeId { get; set; }
public virtual ClimbingGrade grade { get; set; }
[Display (Name = "Routename")]
public string name { get; set; }
[Display(Name = "Color")]
public int colorId { get; set; }
public virtual GripColor color { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display (Name ="Date set")]
public DateTime dateSet { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display (Name ="Date removed")]
public DateTime? dateRemoved { get; set; }
[Display (Name ="Marked for removal")]
public bool markedForRemoval { get; set; }
}
The controller:
public ActionResult Index()
{
var routes = db.Routes.Include(r => r.color).Include(r => r.grade).Include(r => r.rope).Include(r => r.routeSetter).Include(r => r.secundaryRouteSetter);
ViewBag.Page = "Routes";
return View(routes.ToList());
}
Now the color property is always null. while all other properties are loaded.
I can't seem to figure this one out. Any help would be welcome
EDIT
The GripColor clas:
public class GripColor
{
[Key]
public int GripColorId { get; set; }
[Display(Name = "Primary color")]
public string primaryColor { get; set; }
[Display(Name = "Secundary color")]
public string secundaryColor { get; set; }
public string displayName { get { return primaryColor + ' ' + secundaryColor; } }
public virtual List<Route> Routes { get; set; }
}
I assume the gripColors are OK in the database;
ViewBag.ColorID = new SelectList(db.Colors, "GripColorId", "displayName");
The above is used to populate a dropdown (wich works) And the colorId is stored correctly in the database
There is no foreign key relating the two tables, then how are you expecting to make inner joins between them?You should setup the relationship between these two tables and define the foreign key.You can use data annotations for this purpose or i highly recommend using fluent api.Check out this documentation for more info:
http://docs.efproject.net/en/latest/modeling/index.html
I'm a beginner and I want to display menu on the left side like This Website and when user clicks on any Category Name or its Sub Category Name I want to display Products related to the clicked category.
I've created 4 tables in my database.
Category
CategoryId(pk), CategoryName, Description, Icon
SubCategory
SubCategoryId(pk), SubCategoryName, Description, Icon,CategoryId(fk)
SubSubCategory
SubSubCategoryId(pk), SubSubCategoryName, Description, Icon, SubCategoryId(fk)
Products
ProductId(pk), Name, Price, Description, CategoryId(fk), SubCategoryId(fk), SubSubCategoryId(fk)
Category.cs Model
public partial class Category
{
public Category()
{
Products = new HashSet<Product>();
SubCategories = new HashSet<SubCategory>();
}
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public string Icon{ get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<SubCategory> SubCategories { get; set; }
}
SubCategory.cs
public partial class SubCategory
{
public SubCategory()
{
Products = new HashSet<Product>();
SubSubCategories = new HashSet<SubSubCategory>();
}
[Key]
public int SubCategoryId { get; set; }
public string SubCategoryName { get; set; }
public int? CategoryId { get; set; }
public string Description { get; set; }
public string Icon{ get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<SubSubCategory> SubSubCategories { get; set; }
}
SubSubCategory.cs
public partial class SubSubCategory
{
public SubSubCategory()
{
Products = new HashSet<Product>();
}
[Key]
public int SubSubCategoryId { get; set; }
public string SubSubCategoryName { get; set; }
public int? SubCategoryId { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual SubCategory SubCategory { get; set; }
}
Product.cs
public partial class Product
{
public int ProductId { get; set; }
public int? CategoryId { get; set; }
public int? SubCategoryId { get; set; }
public int? SubSubCategoryId { get; set; }
public string Name { get; set; }
[AllowHtml]
public string Description { get; set; }
public decimal? Price { get; set; }
}
You should try to first load the whole collection that you want to use in the current view.
Then use lambda expressions or predicates to sort the data into categories e.g
var list = wholeList.Where(i => i.category == "{category-name}");
then load this list to the view templates.
This method is both fast and convenient
On Click of Category, SubCategory, Sub Sub Category,
You should try below MVC way to load partials. Use appropriate overload of this.
#Ajax.ActionLink( ....)
Remember to use targetId in which element your called partial will load.
Your Layout must include jquery and jquery.unobtrusive-ajax. (jquery version must be higher than 1.9)