Get/set issue getting with join query in entities - c#

I want to fill a data in public IList<Order> OrderList { get; set; } with join 2 table. for that i have written a code in dbEntities below
using (var db = new dbEntities())
{
OrderList = (from row in db.Orders
join rowjoin in db.Users on row.UserId equals rowjoin.Id
orderby row.OrderNumber
select new { row.Id, row.UserId, row.TechnicianId, row.OrderNumber, row.ModelName,
row.ServiceName,row.IconUrl,row.Cost,row.Position, row.Status, rowjoin.FirstName ,
rowjoin.LastName, rowjoin.MobileNumber, rowjoin.Email,rowjoin.City, rowjoin.Address}).ToList();
}
its giving an error 2:
Cannot implicitly convert type System.Collections.Generic.List<AnonymousType#1> to System.Collections.Generic.IList<Mobileappy.Order>. An explicit conversion exists (are you missing a cast?)
How do i fix it?

Your query is not returning Order objects but an anonymous type.
If you want to get a List<Order> you must select row instead of select new {...}.

Your OrderList property needs to be a new type that can hold combination of both User and Order(like ViewModel). You can create properties for newly created type in two ways.
1. Create all required properties(User's properties + Order's proeperties) for newly created viewmodel and assign values thru the linq query.
public class OrderUserVM
{
public int OrderNumber { get; set; }
...
public string FirstName { get; set; }
...
}
public IList<OrderUserVM> OrderList { get; set; }
OrderList = (from row in db.Orders
join rowjoin in db.Users on row.UserId equals rowjoin.Id
orderby row.OrderNumber
select new OrderUserVM
{
OrderNumber = row.OrderNumber,
...
FirstName = rowjoin.FirstName,
....
}).ToList();
OR
2. Create only two properties of type 'User' and 'Order' for newly created viewmodel and assign values thru the linq query.
public class OrderUserVM
{
public User User { get; set; }
public Order Order { get; set; }
}
public IList<OrderUserVM> OrderList { get; set; }
OrderList = (from row in db.Orders
join rowjoin in db.Users on row.UserId equals rowjoin.Id
orderby row.OrderNumber
select new OrderUserVM
{
Order = row,
User = rowjoin,
}).ToList();

You need to declare a new Type (OrderUser) with the info of both the Order and the User. Then, instead of use select new {...} you must use select new OrderUser(){ UserName = rowjoin.FirstName, OrderId = row.Id, ... }. Change public IList<Order> OrderList { get; set; } by public IList<OrderUser> OrderList { get; set; }

Related

How to join table in LINQ with aspnetusers and then create new object with results for ViewModel

just want to know what I should be adding in the select new block to retrieve SQL query result.
I have a BlogViewModel, and two tables blog and users. I want to join the two tables get the result and then have this in a object I can pass to View.
public IActionResult Index()
{
List<BlogViewModel> blogs = _db.blog.ToList(); //add elements into blogs list
List<IdentityUserHelper> users = _db.Users.ToList(); //add elements into users
var result = from b in blogs //"blogs" is list
join u in users //"users" is list
on b.userID equals u.Id into group1 //join tables blogs with aspnetusers
select new //below is object initliazer
{
//I want to join table with aspnetusers?? don't know what to put in here
};
var blogList = new List<BlogViewModel>(); //create list for blogs
foreach (var test in result) //iterate through queryresult
{
blogList.Add(new BlogViewModel
{
blogID = test.blogID,
blogContent = test.blogContent
userID = test.userID
}
);
public class BlogViewModel
{
[Key]
public int blogID { get; set; }
public string title { get; set; }
public string blogContent { get; set; }
public string author { get; set; }
public string userID { get; set; }
public DateTime publishedDate { get; set; }
}
You can select desired fields for the result with the desired aliases:
var result = from b in blogs
join u in users
on b.userID equals u.Id into group1 //join tables blogs with aspnetusers
select new //below is object initliazer
{
blogID = b.blogID,
blogContent = b.blogContent,
userID = b.userID,
author = u.Name
};
also, you can select new BlogViewModel directly in the result instead of select new and you won't need using foreach in order to return list of BlogViewModel items.
You certainly don't need foreach loop here. Try this
var model = from b in blogs
join u in users
on b.userID equals u.Id into bj
from b in bj.DefaultIfEmpty()
select new BlogViewModel
{
blogID = b.blogID,
blogContent = b.blogContent
userID = u.userID
author =u.Name
}
};
return View(model);

Comparing two table IDs. ASP.NET MVC

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

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.

How to join two customer lists into one list

I have two classes:
1. a customer class, which contains the id and name of the customer
2. a customer_details class, which contain the address of the customer and so on
class customer
{
public int customer_id { get; set; }
public string name { get; set; }
//and so on
}
class customer_details
{
public int customer_id { get; set; }
public string address { get; set; }
//and so on
}
My question is, how can I join a List<customer> and a List<customer_details> to a single list, so it shows me the customer_id, name and address in a single list...
Thanks for your answers
You must use the Join Method
Here is an example with your classes
List<customer> customers = new List<customer>();
List<customer_details> details = new List<customer_details>();
var query = (from c in customers
join d in details on c.customer_id equals d.customer_id
select new
{
c.customer_id,
c.name,
d.address,
}).ToList();
Following is the example using Fluent syntax, which is rather compact and preferred:
customers.Join(
details,
c=>c.customer_id,
d=>d.customer_id,
(c,d)=>new {c.customer_id, c.name, d.address}
).ToList()

Retrieving the username from MembershipUser for a join query

I'm newer using C#, linq. I'm trying to add the UserName into a query to show it as part of a DataSource of a ListView, I have tested several way to joined, but always I m'receiving next error:
"Unable to create a constant value of type 'Web.Admin.system.User'. Only primitive types or enumeration types are supported in this context."
My code is:
//Entities
public class Category
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class Order
{
public Guid Id { get; set; }
public string Description { get; set; }
public Guid CategoryId { get; set; }
public Guid UserId { get; set; }
}
//class added just for getting the user list (possibly, I do not need)
public class User
{
public Guid Id { get; set; }
public String Name { get; set; }
}
Here is my code preparing the filter
//retrieve the data from Order and Category
IQueryable<Order> orders = orderService.GetAllOrders();
IQueryable<Category> category = categoryService.GetAllCategories();
//obtain the users
MembershipUserCollection members = Membership.GetAllUsers();
// 1st option for managing users directly with memberShip variable
var memberShip = members.Cast<MembershipUser>().ToDictionary(m => m.ProviderUserKey, m => m.UserName).AsQueryable();
// 2nd option, I have added this code to see if I could manage the users as a list
List<User> users = new List<User>();
foreach (var _member in memberShip)
{
users.Add(new User { Id = (Guid)_member.Key, Name = _member.Value });
}
//Getting information to fill a listview
var DDLsource = from i in orders
join c in category on i.CategoryId equals c.Id
join u in users on i.UserId equals u.Id // 1st I tried to use memberShip directly but gave me error of types
select new
{
i.Id,
i.Description,
CategoryName = c.Name,
UserName = u.Name
};
ListViewOrders.DataSource = DDLsource.ToList();
Here is where the Error is triggered, I'm trying to understand the error and do other solution, I tested the query like:
Example 2
var DDLsource = from i in orders
join c in category on i.CategoryId equals c.Id
select new
{
i.Id,
i.Description,
CategoryName = c.Name,
UserName = (from u in users where u.Id == i.UserId select u.Name)
};
Example 3
var DDLsource = from i in orders
join c in category on i.CategoryId equals c.Id
join u in Membership.GetAllUsers().Cast<MembershipUser>() on i.UserId equals ((Guid)u.ProviderUserKey)
select new
{
i.Id,
i.Description,
CategoryName = c.Name,
UserName = u.UserName
};
all with the same results, could someone give me a hand with my mistake will surely be very obvious. Thanks in advance
I would do something like this (sorry, untested code...):
var DDLsource =
from i in orders
join c in category on i.CategoryId equals c.Id
select new
{
i.Id,
i.Description,
CategoryName = c.Name,
i.UserId,
UserName = ""
};
foreach(var ddl1 in DDLsource)
ddl1.UserName = Membership.GetUser(ddl1.UserId).Name;

Categories

Resources