how to combine the result from differentviews to IQueryable<T> - wpf

i have a list of PlanItems bind to telerik RadGrid and have two views retrieves the result.Each view get different data so how can i get that data into IQueryable
public class PlanItems
{
public int Id{get; set;}
public string Name { get; set; }
public string HV { get; set; }
public string StNumber { get; set; }
public string LDNumber { get; set; }
public string MSId { get; set; }
public string CreatedBy { get; set; }
public string Type { get; set; }
}
I have 2 different views vw_Boys ,vw_Girls and Student Entity
first i got boys_Id and Girls_Id from student Entity
public IQuerable<PlanItems> GetAllStudents()
{
var Id = from v in context.Student
.Include("SBoy")
.Include("SGirl")
where v.CreatedBy_Id == user.Id
select v;
var temp = unp.Select(a=>a.SBoy.boys_Id).Distinct();
var temp1 = unp.Select(a => a.SGirl.girls_Id).Distinct();
var vwboys = from nv in context.vw_boys
where(temp.Contains(nv.SId))
select nv;
var vwgirls= from nv in context.vw_girls
where (temp1.Contains(nv.GId))
select nv;
var Boysresult = from n in vwboys
select new PlanItems
{
Id = n.SId,
Name = n.Name,
HV = n.HV,
StNumber = n.SNumber,
LDNumber = n.LineNumber,
MSId = n.MasterId,
CreatedBy = n.USerName,
Type = n.SubjectType
};
var GirlsResult = from n in vwgirls
select new UnplannedItems
{
Id = n.GiId,
Name = n.Name,
HV = n.GV,
StNumber = n.SujNumber,
LDNumber = n.Lid,
MSId = n.MasterId,
CreatedBy = n.USerName,
Type = n.SubjectType
};
}
my telerikGrid sample
<telerik:GridViewDataColumn Header="StudentID" IsReadOnly="True" DataMemberBinding="{Binding ID, Mdde=OneWay}" />
how can i return the result from above method..how can i combine the result to one.

I would do it something like this.
Add a new property to you class like this. Because you might have to seperate the boys from the girls in a other case:
public class PlanItems
{
public int Id{get; set;}
public string Name { get; set; }
public string HV { get; set; }
public string StNumber { get; set; }
public string LDNumber { get; set; }
public string MSId { get; set; }
public string CreatedBy { get; set; }
public string Type { get; set; }
//new property
public bool IsUnplanned { get; set; }
}
The use a concat between them like this:
var result= (
from n in vwboys
select new PlanItems
{
Id = n.SId,
Name = n.Name,
HV = n.HV,
StNumber = n.SNumber,
LDNumber = n.LineNumber,
MSId = n.MasterId,
CreatedBy = n.USerName,
Type = n.SubjectType,
IsUnplanned=false
}
).Concat
(
from n in vwgirls
select new PlanItems
{
Id = n.GiId,
Name = n.Name,
HV = n.GV,
StNumber = n.SujNumber,
LDNumber = n.Lid,
MSId = n.MasterId,
CreatedBy = n.USerName,
Type = n.SubjectType,
IsUnplanned=true
}
);
Hope this helps

You can union 2 different IQueryable using union extension method :
here's an example

I am not an expert in wpf, but looking at the solution I think you can use a parent class for both Boys and Girls and then add to a list of that class.
lets say both Boy and Girl classes are inherited from Person class, then create
List<Person> personList = new List<Person>()
and add Boys and Girls into this list.
I am not sure whether this is the solution you need

Related

Dapper multi object query One-Many

Not really sure why I'm not getting the child object populated.
My tables:
Product:
[ProductId]
,[Brand]
,[Model]
StoreProduct:
[StoreId]
,[ProductId]
,[StoreProductId]
Class
public class Product
{
public Guid ProductId { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public virtual List<StoreProduct> StoreProducts { get; set; }
}
public class StoreProduct
{
public int StoreId { get; set; } //Key 0
public Guid ProductId { get; set; } //Key 1
public Store Store { get; set; }
public Product Product { get; set; }
public string StoreProductId { get; set; } //A new Id specific for each store
}
My Dapper Code
string sql = "SELECT * FROM StoreProduct AS A INNER JOIN Product AS B ON A.ProductId = B.ProductId WHERE A.StoreProductId = #StoreProductId and A.StoreId = #StoreId";
var connection = AppDbContext.Database.GetDbConnection();
return connection.Query<StoreProduct, Product, Product>(
sql,
(StoreProduct, Product) => { StoreProduct.ProductId = Product.ProductId; return Product; },
new { StoreProductId = storeProductId, StoreId = StoreID }, splitOn: "ProductId")
.FirstOrDefault();
What the DB returns:
But... StoreProducts List is null.
Use Dapper the way it works.
var listProduct = new Dictionary<string, Product>();
var listStoreProduct = new Dictionary<string, StoreProduct>();
using var connection = _connectionProvider.GetConnection();
var query = "SELECT * FROM StoreProduct AS A INNER JOIN Product AS B ON A.ProductId = B.ProductId WHERE A.StoreProductId = #StoreProductId and A.StoreId = #StoreId";
var result = connection.Query<Product, StoreProduct, Product>(query, (product, storeProduct) =>
{
if (!listProduct.TryGetValue(product.Id, out var entry))
{
entry = product;
listProduct.Add(entry.Id, entry);
}
if (storeProduct != null && !listStoreProduct.TryGetValue(storeProduct.Id, out var procInstance))
{
listStoreProduct.Add(procInstance.Id, procInstance);
entry.ProcessInstance.Add(procInstance);
}
return entry;
}, splitOn: "ProductId").Distinct().ToList();
I hope I could have helped you.

Populate two table data using ASP.NET Core

I want to get two table data in ASP.NET Core. I can get one table detail by using model class. then I can show data by using below code.
[HttpGet]
public async Task<ActionResult<IEnumerable<OrderMaster>>> GetOrderDetails()
{
return await _context.OrderDetails.ToListAsync();
}
So my question is how to get two tables data to the above method? As a example I want to retrieve data for below query:
select a.ItemDescription,a.Quantity,a.Amount, a.CustomerCode, b.CustomerName,b.CustomerAddress,b.MobileNumber,b.Email from OrderDetails as a left join CustomerDetails as b ON a.CustomerCode=b.CustomerCode
Thank you
My model classes
public class CustomerMaster
{
[Key]
public int CustomerCode { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string CustomerName { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string CustomerAddress { get; set; }
[Column(TypeName = "nvarchar(10)")]
public string MobileNumber { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string Email { get; set; }
}
public class OrderMaster
{
[Key]
public int OrderId { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string ItemCode { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string ItemName { get; set; }
[Column(TypeName = "nvarchar(MAX)")]
public string ItemDescription { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string Quantity { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string OrderDate { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string Amount { get; set; }
[Column(TypeName = "nvarchar(100)")]
public string CustomerCode { get; set; }
}
this is my Context class
public class AppDbcontext : DbContext
{
public AppDbcontext(DbContextOptions<AppDbcontext> options) : base(options)
{
}
public DbSet<CustomerMaster> CustomerDetails { get; set; }
public DbSet<OrderMaster> OrderDetails { get; set; }
}
}
For how to join two tables,a simple demo you could follow:
var model = (from a in _context.CustomerDetails
join b in _context.OrderDetails
on a.ID equals b.ID
select new {
Name = a.Name,
Address = b.Address
}).ToList();
Update 1:
You use left join sql,you need change like below:
var model = (from a in _context.OrderDetails
join b in _context.CustomerDetails
on a.CustomerCode equals b.CustomerCode.ToString() into ab
from b in ab.DefaultIfEmpty()
select new
{
ItemDescription = a.ItemDescription,
Quantity = a.Quantity,
Amount = a.Amount,
CustomerCode = a.CustomerCode,
CustomerName = b.CustomerName,
CustomerAddress = b.CustomerAddress,
MobileNumber = b.MobileNumber,
Email = b.Email,
}).ToList();
Update 2:
For how to return the two tables data,I think a better way is to create a view model to display:
public class OrderDetailViewModel
{
public string ItemDescription { get; set; }
public string Quantity { get; set; }
public string Amount { get; set; }
public string CustomerCode { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string MobileNumber { get; set; }
public string Email { get; set; }
}
[HttpGet]
public IEnumerable<OrderDetailViewModel> GetOrderDetails()
{
var model = (from a in _context.OrderDetails
join b in _context.CustomerDetails
on a.CustomerCode equals b.CustomerCode.ToString() into ab
from b in ab.DefaultIfEmpty()
select new OrderDetailViewModel
{
ItemDescription = a.ItemDescription,
Quantity = a.Quantity,
Amount = a.Amount,
CustomerCode = a.CustomerCode,
CustomerName = b.CustomerName,
CustomerAddress = b.CustomerAddress,
MobileNumber = b.MobileNumber,
Email = b.Email,
}).ToList();
return model;
}
You have to get the two models connected through navigation properties. Something like
public class Table1 {
int Table1Id;
string Name;
ICollection<Table2> Tables2;
}
public class Table2 {
int Table2Id;
string Address;
Table1 Table1;
}
Then you can have your business layer code
[HttpGet]
... GetNameWithAddresses(int id) {
return (from c in _context.Table1 where c.Table1Id == id
select new { c.Name, c.Tables2 }).ToList();
}
If the tables have primary-foreign key relationship, it will be done automatically for you if you scaffold them. And if you don't have FK relationship, you have to ask yourself why!
Use this code
using (var context = new AppDbcontext())
{
var table1 = context.CustomerDetails.ToList();
var table2 = context.OrderDetails.ToList();
}

MVVM Dapper how to save changed collectionitems instantly to database

I've got a question relating the above mentioned topic.
------Using Dapper and Caliburn Micro-----
At the moment im building a mvvm wpf application which displays a list of orders. These orders need some ressources to be allocated so the workprocess can begin.
The list of orders provide a few buttons for each row (order) to start, pause, finish and to set the status of the order like "is material allocated".
Whats a good practise to save changes of the above steps made via the list to database?
When creating the order I simply pass the values via a buttonclick to a method in database access project.
For the moment lets just talk about the UIOrderModel and the property IsAllocated
Once the Button (the ugly beige one) is clicked the following method fires:
public void MatAllocated(UIOrderModel order) {
order.IsMatAllocated = "Y";
order.IsAllocated = true;
order.StatusFlag = MKDataWork.Library.Enums.StatusFlag.allocated;
OrdersBc.Refresh();
}
Since it's workig so far as it should be I'm on the question how to store the Information about the changed status of Allocation in my database. By way of example it would be kinda easy just to fire an update query (sp) in the method above.
The collection and the database should always have the same state of data.
The UiOrderModel:
public class UIOrderModel {
private UIOrderModel UIorder = null;
public int Code { get; set; }
public UIuserModel OrderedByEmp { get; set; }
public int OrderedByEmpPersId { get; set; }
public string OrderedByEmpName { get; set; }
public List<UIAllocationModel> AllocationList {get;set;}
public DateTime OrderDate { get; set; }
public UIDepartmentModel ForDepartment { get; set; }
public string DepartmentName { get; set; }
public DateTime ExpectedFinishDate { get; set; }
public string Project { get; set; }
public string Commission { get; set; }
public string IsMatAllocated { get; set; } = "N";
public bool IsAllocated { get; set; } = false;
public string Additions { get; set; }
public StatusFlag StatusFlag { get; set; }
public decimal? Quantity { get; set; }
public UnitOfMeasures Unit { get; set; }
public UIitemModel Item { get; set; }
public string ItemName { get; set; }
public string ItemCode { get; set; }
public DateTime FinishedDateTime { get; set; }
public UIuserModel FinishedByEmp { get; set; }
public UIOrderModel() { }
public UIOrderModel(Dictionary<string,object> entries) {
int i = 0;
this.UIorder = this;
this.Code = int.TryParse(entries["Code"].ToString(), out i) ? i : 0;
this.OrderedByEmp = (UIuserModel)entries["OrderedByEmp"];
this.OrderedByEmpPersId = ((UIuserModel)entries["OrderedByEmp"]).PersId;
this.ForDepartment = (UIDepartmentModel)entries["SelectedDepartment"];
this.DepartmentName = ((UIDepartmentModel)entries["SelectedDepartment"]).Bezeichnung;
this.ExpectedFinishDate = (DateTime)entries["ExpectedFinishDate"];
this.Quantity = (decimal?)entries["Quantity"];
this.Unit = (UnitOfMeasures)entries["SelectedUnitOfMeasures"];
this.Item = (UIitemModel)entries["Item"];
this.ItemName = ((UIitemModel)entries["Item"]).ItemName;
this.ItemCode = ((UIitemModel)entries["Item"]).ItemCode;
this.StatusFlag = (StatusFlag)entries["StatusFlag"];
this.Project = (string)entries["Project"];
this.Commission = (string)entries["Commission"];
this.Additions = (string)entries["Additions"];
}
public UIOrderModel(int code,string orderedByEmpName, int orderedByEmpPersId, string departmentName, DateTime expectedFinishDate,
decimal? quantity, UnitOfMeasures unit, string itemname, string itemcode, string project, string commission,
StatusFlag statusFlag, string additions)
{
this.UIorder = this;
this.Code = code;
this.OrderedByEmpPersId = orderedByEmpPersId;
this.OrderedByEmpName = orderedByEmpName;
this.DepartmentName = departmentName;
this.ExpectedFinishDate = expectedFinishDate;
this.Quantity = quantity;
this.Unit = unit;
this.ItemName = itemname;
this.StatusFlag = statusFlag;
this.Project = project;
this.Commission = commission;
this.Additions = additions;
}
public void SaveOrder() {
OrderModel result = (OrderModel)this;
result.SaveOrder();
}
public static explicit operator OrderModel(UIOrderModel uiOrder) {
return new OrderModel()
{
Code = uiOrder.Code,
OrderDate = uiOrder.OrderDate,
OrderedByEmp = (UserModel)uiOrder.OrderedByEmp,
OrderedByEmpName = $"{uiOrder.OrderedByEmp.FirstName} {uiOrder.OrderedByEmp.LastName}",
ExpectedFinishDate = uiOrder.ExpectedFinishDate,
ForDepartment = (DepartmentModel)uiOrder.ForDepartment,
AllocationList = uiOrder.AllocationList?.Select(am => (AllocationModel)am).ToList(),
IsMatAllocated = uiOrder.IsMatAllocated,
Quantity = uiOrder.Quantity,
Unit = uiOrder.Unit,
Item = (ItemModel)uiOrder.Item,
ItemCode = uiOrder.Item.ItemCode,
ItemName = uiOrder.Item.ItemName,
Project = uiOrder.Project,
Commission = uiOrder.Commission,
StatusFlag = uiOrder.StatusFlag,
Additions = uiOrder.Additions
};
}
public static explicit operator UIOrderModel(OrderModel order) {
return new UIOrderModel()
{
Code = order.Code,
OrderDate = order.OrderDate,
OrderedByEmp = (UIuserModel)order.OrderedByEmp,
OrderedByEmpName = $"{order.OrderedByEmp.FirstName} {order.OrderedByEmp.LastName}",
ExpectedFinishDate = order.ExpectedFinishDate,
ForDepartment = (UIDepartmentModel)order.ForDepartment,
AllocationList = order.AllocationList?.Select(am => (UIAllocationModel)am).ToList(),
IsMatAllocated = order.IsMatAllocated,
Quantity = order.Quantity,
Unit = order.Unit,
Item = (UIitemModel)order.Item,
ItemCode = order.ItemCode,
ItemName = order.ItemName,
Project = order.Project,
Commission = order.Commission,
StatusFlag = order.StatusFlag,
Additions = order.Additions
};
}
}
But whats the correct MVVM way to accomplish this in a proper manner?
Thanks for an advice!
Well I've been on vacation, returned and had some time and distance to the question above. Yesterday I chose a kinda simple way to solve it.
I've implemented the command pattern and passed the execution through my UI project to the data access. It's just one query for all kinds of statussteps (and the relating table) and updates of the whole order. Therefore I pass an enum value (action), orderNo and Id of the employee as parameter for the method / query.
I'm not completely sure if it's the best mvvm way but its working in a comfortable and fast way.

dapper join splitOn multi column key

i'm working in new company with huge db...
i'm trying to introduce dapper as orm...
i've got a relation 1-N between two tables, with multi PK
my query is something like
SELECT *
FROM testmag INNER JOIN movmag ON
movmag.code= testmag.code AND
tm_type = mm_type
AND tm_year = mm_year
AND tm_serie = mm_serie
AND tm_documentNumber = mm_documentNumber
and my table class models:
public class testMag
{
[Key]
[Column(Order = 0)]
public string code{ get; set; }
[Key]
[Column(Order = 1)]
public string tm_type { get; set; }
[Key]
[Column(Order = 2)]
public short tm_year { get; set; }
[Key]
[Column(Order = 3)]
public string tm_serie { get; set; }
[Key]
[Column(Order = 4)]
public int tm_documentNumber { get; set; }
...
}
public class movMag
{
[Key]
[Column(Order = 0)]
public string code { get; set; }
[Key]
[Column(Order = 1)]
public string mm_type { get; set; }
[Key]
[Column(Order = 2)]
public short mm_year { get; set; }
[Key]
[Column(Order = 3)]
public string mm_serie { get; set; }
[Key]
[Column(Order = 4)]
public int mm_documentNumber { get; set; }
[Key]
[Column(Order = 5)]
public int mm_row { get; set; }
...
}
i'm trying these dapper query, with only one splitOn key and with all keys
string qJoin2 = "SELECT top 10 * FROM testmag INNER JOIN movmag ON movmag.code= testmag.code AND tm_type = mm_type AND tm_year = mm_year AND tm_serie = mm_serie AND tm_documentNumber = mm_documentNumber ";
var res = connection.Query<movmag, testmag, Tuple<movmag, testmag>>(
qJoin2,
Tuple.Create,
splitOn: "code,tm_type,tm_year,tm_serie,tm_documentNumber,code,mm_type,mm_year,mm_serie,mm_documentNumber,mm_row").ToList();
var res2 = connection.Query<movmag, testmag, Tuple<movmag, testmag>>(
qJoin2,
Tuple.Create,
splitOn: "code").ToList();
where i'm wrong?
someone could explain me!?
many thanks
i've changed type order in dapper.query()
and it works on both
var res = connection.Query<testmag, movmag, Tuple<testmag, movmag>>(
qJoin2,
Tuple.Create,
splitOn: "codditt,tm_tipork,tm_anno,tm_serie,tm_numdoc,codditt,mm_tipork,mm_anno,mm_serie,mm_numdoc,mm_riga").ToList();
var res2 = connection.Query<testmag, movmag, Tuple<testmag, movmag>>(
qJoin2,
Tuple.Create,
splitOn: "codditt").ToList();

Nested List Item reflecting type error

I have a model that contain variables and a list of another class instance..
here models:
public class patient
{
[XmlElement("firstname")]
public string name { get; set; }
[XmlElement("lastname")]
public string surname { get; set; }
[XmlElement("age")]
public int age { get; set; }
[XmlElement("gender")]
public string gender { get; set; }
[XmlArray("exams"), XmlArrayItem(typeof(exam), ElementName = "exam")]
public List<exam> exam { get; set; }
}
public class exam
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement(ElementName = "date", DataType = "DateTime")]
public DateTime date { get; set; }
[XmlElement("comment")]
public string comment { get; set; }
}
List<exam> examsLocal = new List<exam>(){
new exam{ id = "id of patient 1", date = DateTime.Now, comment = "coomment exam1" },
};
List<patient> overview = new List<patient>();
try
{
var b = new List<patient>()
{
new patient{ name = "name of patient 1", surname = "surname of patient 1", gender = "Female", age = 31, exam=examsLocal },
};
var writer = new System.Xml.Serialization.XmlSerializer(typeof(List<patient>));//throw exception
the line throws exceptions works fine if I delete 'exam=examsLocal' varible from List..
What is the correct way of serialize nested List items
Update your class definition of exam to be looks like:
remove the DataType of Date Property because the System.DateTime not allowed in Xml Serialization:
public class exam
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement(ElementName = "date")]
public DateTime date { get; set; }
[XmlElement("comment")]
public string comment { get; set; }
}
And update the Property declaration in patiant class:
[XmlArray("exams"), XmlArrayItem(typeof(exam), ElementName = "exams")]
public List<exam> exams { get; set; }

Resources