Comparing two table IDs. ASP.NET MVC - c#

I am currently loading two Orders and Colors tables, I wanted the Colors table to list the items that have the ID equal to Orders. For this, what occurred to me was to assign the IdOrders values ​​to a variable and compare it with my IdOrders (in my table Colors), but it is not possible to assign the database's balance to my variable
My tables:
public partial class Orders
{
public int ID_Orders { get; set; }
public Nullable<System.DateTime> Data_Registo { get; set; }
public string Num_Encomenda { get; set; }
public string Ref_Cliente { get; set; }
}
public partial class Colors
{
public int ID_Orders { get; set; }
public int ID_Programa_Malha { get; set; }
public int ID_Linha_Cor { get; set; }
public string Cor { get; set; }
}
I am working with a database already in operation and possible these tables are already used in a sql join but not how to process that information.
As I said the first thing I remembered was to do this:
My Controller:
var id = from d in db.Orders
select d.ID_Orders;
var color = db.Colors.Where(x => x.ID_Orders = id).ToList();
var tables = new EncomendaViewModel
{
Orders= db.Orders.ToList(),
Colors= color.ToList(),
};
return View(tables);
Error in id: CS0029 C# Cannot implicitly convert type to 'int'
Is it possible to process the data in this way?
Thanks for anyone who can help!
-------------------(Update)------------------------------------------------
Using == cs0019 operator '==' cannot be applied to operands of type
My view in Broswer
dbEntities sd = new dbEntities();
List<Orders> orders= sd.Orders.ToList();
List<Colors> colers= sd.Colors.ToList();
var multipletable = from c in orders
join st in colers on c.ID_Programa equals st.ID_Programa into table1
from st in table1.DefaultIfEmpty()
select new MultipleClass { orders= c, colers= st };

There could be one or more values returned from the below query.
var id = from d in db.Orders
select d.ID_Orders;
That is the reason why it was throwing an error.
So lets try it this way
var color = db.Colors.Where(x => id.Contains(x.ID_Orders)).ToList();

public class OrderWithColorsViewModel
{
public Order order { get; set; }
public List<Colors> colers{ get; set; }
}
Public class TestOrderController : Controller
{
public DailyMVCDemoContext db = new DailyMVCDemoContext();
public ActionResult Index()
{
var orders= db.Orders.ToList();
var colers = db.Colors.ToList();
var result = (from c in orders
join st in colers on c.ID_Orders equals st.id into table1
select new OrderWithColorsViewModel { order =c, colers =
table1.ToList() }).ToList();
return View(result);
}
}
credits: YihuiSun

Related

join data in linq if only data for object is available from view model - ASP.net -mvc5

I have viewModel that extract of multiple model classes. I am binding data and then passing to razor partial view to show data however I am getting error if one of the model object is null. In my business process it is expected however my question is can I use if condition is Linq--Joins i.e. that join result only if data exist in database or is there any better way to do it.
public StudentDetailedProfileViewModel GetStudentDetailedProfileByStudentID(int _studentID)
{
try
{
using (var _uow = new StudentProfile_UnitOfWork())
{
StudentDetailedProfileViewModel StudentProfileObject = new StudentDetailedProfileViewModel();
var _profile = (from _student in _uow.Student_Repository.GetAll()
join _contactDetail in _uow.ContactDetail_Repository.GetAll() on _student.StudentID equals _contactDetail.StudentID
join _addressDetail in _uow.Address_Repository.GetAll() on _student.StudentID equals _addressDetail.StudentID
join _studentCourse in _uow.Course_Repository.GetAll() on _student.StudentID equals _studentCourse.StudentID
join _school in _uow.School_Repository.GetAll() on _studentCourse.SchoolID equals _school.SchoolID
join _campus in _uow.Campus_Repository.GetAll() on _studentCourse.CampusID equals _campus.CampusID
where _student.StudentID == _studentID
select new StudentDetailedProfileViewModel { _studentModel = _student, _contactDetailModel = _contactDetail, _addressModel = _addressDetail , _courseModel = _studentCourse,_schoolModel = _school, _campusModel = _campus}).FirstOrDefault();
_profile._emergencyContactModel = (from _emergencyContact in _uow.EmergencyContact_Repository.GetAll()
where _emergencyContact.StudentID == _studentID
select _emergencyContact).ToList();
return _profile;
}
}//
catch { return null; }
}
......
public class StudentDetailedProfileViewModel
{
public StudentDetailedProfileViewModel() { }
public Student _studentModel { get; set; }
public Course _courseModel { get; set; }
public School _schoolModel { get; set; }
public Campus _campusModel { get; set; }
public ContactDetail _contactDetailModel { get; set; }
public Address _addressModel { get; set; }
public List<EmergencyContact> _emergencyContactModel { get; set; }
}
Instead of JOINing, if your root entity (Student) has navigation properties to the child collections (and the associations are configured in your entity model) you could Include() them. Let LINQ generate the select statement rather than trying to figure it out beforehand.

Add data to a list insde a list where item in the prerent list

I would like to select a where statement that adds items to a list where only product codes match. I have it so it gets all of the products sold in the sale but I would like there were statement to get only products in this sale.
PS: This is really hard to explain
Model
public class userSales
{
public string Name { get; set; }
public string UserName { get; set; }
public int Sale_Id { get; set; }
public int CostumerID { get; set; }
public string Sale_Date { get; set; }
public string Paid { get; set; }
public Nullable<int> Sale_Cost { get; set; }
public string Discount_Code { get; set; }
public List<SaleProduct> saleProductsList { get; set; }
}
public class SaleProduct
{
public int SaleID { get; set; }
public string ProductCode { get; set; }
public int ProductCount { get; set; }
public string Image_Path { get; set; }
public string Shoot_Date { get; set; }
public string Shoot_Info { get; set; }
}
Linq statement where I'm having trouble:
var test = (from _ClientData in db.ClientDatas
join _salesInfo in db.Sales_Infoes
on _ClientData.CostumerID
equals _salesInfo.CostumerID
where _ClientData.UserName == _userName
select new userSales()
{
CostumerID = _ClientData.CostumerID,
Name = _ClientData.Name,
UserName = _ClientData.UserName,
Sale_Id = _salesInfo.Sale_Id, // This is the item i would like to use in my were statement
Sale_Date = _salesInfo.Sale_Date,
Sale_Cost = _salesInfo.Sale_Cost,
Discount_Code = _salesInfo.Discount_Code,
Paid = _salesInfo.Paid,
// Problem here
saleProductsList = db.SaleProducts.Where()
}).ToList();
Got to this based on the answer:
var reult = db.ClientDatas.Where(a => a.UserName == _userName)
.Join(db.Sales_Infoes,
a => a.CostumerID,
b => b.CostumerID,
(a, b) => new userSales()
{
CostumerID = a.CostumerID,
Discount_Code = b.Discount_Code,
Sale_Cost = b.Sale_Cost,
Sale_Id= b.Sale_Id,
Name = a.Name,
Sale_Date = b.Sale_Date,
UserName = a.UserName,
Paid = b.Paid,
saleProductsList = db.SaleProducts.Where(c => c.SaleID == b.Sale_Id).ToList()
}).ToList();
You're not looking for a where, you're looking for a join. Where filters the results on a single table, join intersects two tables which is actually what you want here.
var result = db.Sales_Infoes.Where(x => x.UserName == _userName)
.Join(db.ClientDatas,
x => x.Sale_Id,
y => y.Sale_id,
(x, y) => new userSales() {
// x is SalesInfo obj y is ClientDatas obj do assignement here
Name = y.Name,
Sale_Date = y.Sale_date
}).ToList();
Just fyi I haven't had a chance to test that but it's the basic idea. You don't need a select like in your statement because the last argument I'm passing into join is the lambda (x, y) => ... in that case x and y are the current row from each table (that we've gotten from applying our where to the user sales table then joining those results into the salesproduct table) so whatever projections you want to do occur there. The other two method args above that are the telling join which fields to compare, it's the 'key selector' lambda expression for each table.

Assign List property on Select LINQ statement

So i want to achieve something like:
var query = from p in db.Project
select new A
{
Project = p,
Capacity = new List<Capacity>((from pp in db.ProjectActualCapacity
where pp.ProjectID == p.ID
select new Capacity
{
Actual = pp.Hours,
Date = pp.Date,
ProjectID = pp.ProjectID
}
).ToList())
};
However, when the query is converted to list. It throws the following error
Only parameterless constructors and initializers are supported in LINQ to Entities.
Is there a workaround to this?
thanks
//Update
public class Capacity
{
public DateTime Date { get; set; }
public decimal? Actual { get; set; }
public decimal? Projected { get; set; }
public int ProjectID { get; set; }
public decimal Rate { get; set; }
}
You are explicitly creating a list and using the constructor which accepts an enumerable. This is not necessary since you are already using .ToList() where you define that collection.
Also, your Capacity class needs a parameterless constructor.
So I think it will work like this.
var query = from p in db.Project
select new A {
Project = p,
Capacity = (from pp in db.ProjectActualCapacity
where pp.ProjectID == p.ID
select new Capacity {
Actual = pp.Hours,
Date = pp.Date,
ProjectID = pp.ProjectID
}
).ToList())
};

Given a list of items, each containing a subitem, get the subitems and remove duplicates

Given a list of groupos, where each groupo has a single empresa and multiple groupos can have the same empresa, how do you get the empresas that contain any of the list's groupos?
I have this Model:
public class Grupo
{
public int id { get; set; }
public string descripccion { get; set; }
[ForeignKey("Empresas")]
public int empresa { get; set; }
public virtual empresa Empresas { get; set; }
}
public class empresa
{
public int id { get; set; }
public string descripcion { get; set; }
public virtual ICollection<Grupo> Grupos { get; set; }
}
So this method gives me a List
private List<Grupo> VerEmpresas(int userId)
{
var lista = (from ga in db.GrupoAccesos
join g in db.Grupos
on ga.grupo equals g.id
where ga.usuario == userId
select g).ToList();
return lista;
}
and now I want to use this method to show me the empresas that are related to grupo.
Below emp gives a bool, and instead I want all the empresas that are in my list of grupos.
List<Grupo> verEmpresa = VerEmpresas(1);
var emp = (from p in db.Empresas
select p.Grupos).Contains(verEmpresa);
ViewBag.empresa = new SelectList(emp, "id", "descripcion");
You can try getting the empresa ids from your Grupo list and using the foreign key relationship to get the empresas:
var empresaIds = verEmpresa.Select( v => v.empresa ).Distinct().ToList();
var emp = from p in db.Empresas
where empresaIds.Contains( p.id )
select p;
In your code you are passing 'VerEmpresa' which is a list of Grupo. You should pass one object of Grupo from that list. Try using Any and All method on verEmpresa List.
Try something like:
from p in db.Empresas
where verEmpresa.Any(val => p.Contains(val))
select p;
If all you want is the empresas, try:
var emp = (from e in db.Empresas
from g in db.Grupos
where e.Grupos.Contains(g)
select e);

searching a List<>

I have a List<Order>
public int OrderID { get; set; }
public string CustID { get; set; }
public string Details { get; set; }
I want to write a method that accepts a ID, then searches this List for matching records that have same CustID and returns ORderID and Details in a List<>
This will get a sequence of Order objects that match the criteria:
var ordersIWant = myList.Where(order => order.CustID == "some customer ID");
public List<Order> Get(string id)
{
List<Order> orders = new List<Order>(); // pass this in as a param or globally refer to it
var query = from o in orders
where o.CustID == id
select o;
return query.ToList();
}
Or if you want to specifically return only those two fields maybe something like:
public class Order : IOrderDetails
{
public int OrderID { get; set; }
public string CustID { get; set; }
public string Details { get; set; }
}
public interface IOrderDetails
{
int OrderID { get; set; }
string Details { get; set; }
}
public List<IOrderDetails> Get(string id)
{
List<Order> orders = new List<Order>(); // pass this in as a param or globally refer to it
var query = from o in orders
where o.CustID == id
select o as IOrderDetails;
return query.ToList();
}
Assuming those properties you listed belong to a class.
string searchId="15";
var list = (from item in myList
where item.OrderId == searchId
select new {OrderId= item.OrderId,Details = item.Details }).ToList();
Just wrote that without compiling... good luck.
Since you only wanted OrderID and Details I returned an anonymous object. Could also just return item.

Categories

Resources