public class EmpModel
{
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Gender Gender { get; set; }
public int DepartmentId { get; set; }
}
#region [ Enumeration]
public enum Gender
{
Male = 0,
FeMale = 1
}
Now how to get enum value
var employees = root.Elements("Employee");
foreach (var element in employees)
{
var employee = new EmpModel
{
UserName = element.Element("UserName").Value,
FirstName = element.Element("FirstName").Value,
LastName=element.Element("LastName").Value,
Age=Convert.ToInt32( element.Element("Age").Value),
Gender= element.Element("Gender").Value, // On this line shows error
DepartmentId=Convert.ToInt32(element.Element("Department").Value)
};
Thanks
Enumerations in C# are represented by integers (Int32) internally by default. So in this case, if your XML file contains the string "0" or "1", you can simply parse it and then cast it the the correct enum type:
Gender = (Gender) Int32.Parse(element.Element("Gender").Value);
If you are reading strings that correspond to the names of the Enumeration, you should use Enum.Parse():
Gender = (Gender) Enum.Parse(typeof(Gender), element.Element("Gender").Value);
Related
I have two tables with data for veterinary medicine.
Customers have many patients(pats), relation is "one to many".
I want to show customers with their petsname and count single line
Table: Customer
public class Customer
{
[Key]
public int ID { get; set; }
public bool IsActive { get; set; }
public string TC { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Note { get; set; }
public int AccountID { get; set; }
}
Table: Patient (Pet)
public class Patient
{
[Key]
public int PatientID { get; set; }
public bool IsActive { get; set; }
public int TypePatientID { get; set; }
public string TypeRace { get; set; }
public string CIPCode { get; set; }
public string Color { get; set; }
public string PatientName { get; set; }
public int Status { get; set; }
public int GenderID { get; set; }
public DateTime BirthDate { get; set; }
public DateTime? DeathDate { get; set; }
public int CustomerID { get; set; }
public int AccountID { get; set; }
}
public class CustomerPageModel
{
[Key]
public int ID { get; set; }
public bool IsActive { get; set; }
public string TC { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Note { get; set; }
public int AccountID { get; set; }
public string Pats { get; set; }
public int PatCount { get; set; }
}
I tried the following code:
var result = from p in context.Customers
join f in context.Patients on p.ID equals f.CustomerID
where p.AccountID == AccountID
group f by new { f.CustomerID, p.IsActive, p.TC, p.Name, p.Surname, p.Email, p.Address, p.Phone, p.Note, p.AccountID, f.PatientName,p.ID } into g
select new CustomerPageModel
{
ID=g.Key.ID,
IsActive = g.Key.IsActive,
TC = g.Key.TC,
Name = g.Key.Name,
Surname = g.Key.Surname,
Email = g.Key.Email,
Address = g.Key.Address,
Phone = g.Key.Phone,
Note = g.Key.Note,
AccountID = g.Key.AccountID,
Pats = string.Join(",", g.Select(x => x.PatientName))
};
Expected Result is:
[
{
"id":13,
"isActive":true,
"tc":"1234",
"name":"John ",
"surname":"Snow",
"email":"",
"address":"",
"phone":"",
"note":null,
"accountID":3,
"pats":"Oscar,Puffy",
"patCount":2
},
{
"id":14,
"isActive":true,
"tc":"2345",
"name":"Mark",
"surname":"Zurk",
"email":"",
"address":"",
"phone":"",
"note":null,
"accountID":3,
"pats":"Mars",
"patCount":1
}
]
Please check link:
https://dotnetfiddle.net/rsv45D
Can anyone help me to write this ef query?
Why Group by all the fields, as you just want to group by user that should be CustomerID (or whatever its key field is):
var result = from p in customers
join f in patients on p.ID equals f.CustomerID
where p.AccountID == AccountID
group new { f, p } by f.CustomerID into g
select new CustomerPageModel
{
ID = g.Key,
IsActive = g.First().p.IsActive,
TC = g.First().p.TC,
Name = g.First().p.Name,
Surname = g.First().p.Surname,
Email = g.First().p.Email,
Address = g.First().p.Address,
Phone = g.First().p.Phone,
Note = g.First().p.Note,
AccountID = g.First().f.AccountID,
Pats = string.Join(",", g.Select(x => x.f.PatientName)),
PatCount = g.Count()
};
Demo Link
I am trying to join results from three linq queries. The types are as follows:
orderItems is a List<OrderLineItem>
transitTimes is a Dictionary<int,int> where Key = SiteId and Value = TransitDays
shippingPriority is a Dictionary<int,int> where Key = DefaultPriority and Value = SiteId
public class OrderLineItem
{
public decimal OrderLineWorkId { get; set; }
public string Sku { get; set; }
public string SiteId { get; set; }
public char FlagSlapType { get; set; }
public char FlagTruck { get; set; }
public string SkuType { get; set; }
public int QtyOrdered { get; set; }
public int QtySellable { get; set; }
}
public class OrderAllocation
{
public int SiteId { get; set; }
public int TransitDays { get; set; }
public int QtyItemsInStock { get; set; }
public int QtyParcelInStock { get; set; }
public int DefaultPriority { get; set; }
}
Here is my linq query, but it always returns 0 results. Not sure where I am going wrong?
var results = (from i in orderItems
join t in transitTimes on i.SiteId equals t.Key.ToString()
join d in shippingPriority on t.Key equals d.Value
group i by i.SiteId into g
select new OrderAllocation()
{
SiteId = Convert.ToInt32(g.Key),
TransitDays = transitTimes.Select(x => x.Value).FirstOrDefault(),
QtyItemsInStock = g.Count(e => e.QtySellable >= e.QtyOrdered),
QtyParcelInStock = g.Count(e => e.QtySellable >= e.QtyOrdered && e.FlagSlapType != 'Y'),
DefaultPriority = defaultShippingPriority.Select(x => x.Key).FirstOrDefault()
}).OrderBy(x => x.SiteId).ToList();
UPDATE
I found what was wrong, the SiteId of type string had a values with a prefix 0 (ie 01, 02, etc) and therefore would not join with values like 1, 2, etc. Changed type from string to int and am now getting results. Sorry for the false alarm.
The issue may be related to differences in the data types:
(from i in orderItems
join t in transitTimes on i.SiteId equals t.Key.ToString()
orderItems defines SiteId as an string
public string SiteId { get; set; }
while transitTimes has a key of int
Dictionary<int,int>
The join condition of int to string may not provide the results you are expecting.
I've got this class
public class Materiale
{
public string IdMateriale { get; set; }
public string GenereMateriale { get; set; }
public string Categoria { get; set; }
public string Modello { get; set; }
public string Tipo { get; set; }
public string NumSerie { get; set; }
public int Anno { get; set; }
public string DittaCostruttrice { get; set; }
public string Note { get; set; }
public List<Controllo> Controlli = new List<Controllo>();
}
public class Controllo
{
public string IdControllo { get; set; }
public DateTime DataControllo { get; set; }
public string IdMateriale { get; set; }
public string Utente { get; set; }
public string Stato { get; set; }
public string Note { get; set; }
}
I want to query a list of "Materiale" filtering "Controlli". I need to retrieve all properties of the "Materiale" class and only one property of the "Controllo" class (the one named "Stato"). From the list "Controlli" I need the one that has the most recent "DataControllo" property.
I try this in a LINQ query but I receive an error (Max doesn't exist in the current context)
List<Materiale> m = new List<Materiale>();
List<Materiale> m2 = (from ma in m
from c in ma.Controlli
where c.DataControllo == Max(c.DataControllo)
select new
{
ma, c.Stato
}).ToList();
Can someone help me
#Christos is correct, here is my version with let in query syntax:-
List<Materiale> m2 = from m in MaterialeList
let RecentControllo = m.OrderByDescending(x => x.DataControllo)
.FirstOrDefault()
select new Materiale
{
IdMateriale = m.IdMateriale,
GenereMateriale = m.GenereMateriale,
//Similarily other properties of Materiale here
Stato = RecentControllo != null ? RecentControllo.Stato : ""
}).ToList();
I think that you need something more simple like the following one:
List<Materiale> m2 = from ma in m
let mostRecentControllo = ma.Controlli
.OrderByDescending(c=>c.DataControllo)
.FirstOrDefault()
select new
{
Materiale = ma,
Stato = mostRecentControllo != null
? mostRecentControllo.Stato : null
}).ToList();
I have supposed that each Materiale's Controlli list contains Controllo with the same IdMateriale.
While coding I had came across a LINQ query that I was able to accomplish in query syntax but not in lamda syntax. While this works fine in the application, I wanted to learn the query syntax for what I was trying to do.
Essentially, I have a database with views, CO_Leather_V and CO_LeatherSizeColor_V. I also have two classes, CuttingOrder and CuttingOrderDetail. CuttingOrderDetail contains entirely string,int and float properties. The CuttingOrder Class contains 2 string properties and a List of CuttingOrderDetails.
public class CuttingOrder
{
public string cuttingOrderNo { get; set; }
public string reserveSalesOrderNo { get; set; }
public List<CuttingOrderDetail> details { get; set; }
}
public class CuttingOrderDetail
{
public string cuttingOrderNo { get; set; }
public string reserveSalesOrderNo { get; set; }
public string itemCode { get; set; }
public string material { get; set; }
public string color { get; set; }
public string size { get; set; }
public int qty { get; set; }
public float squareFeet { get; set; }
public float squareFeetUsed { get; set; }
}
The query expression I used to get a list of all CuttingOrders with a given SalesOrder was
cos = (from l in db.CO_Leather_Vs
where l.orderNo == Globals.orderNo
select new Globals.CuttingOrder
{
cuttingOrderNo = "NOT SET",
reserveSalesOrderNo = "FAKE_SO_NO",
details = (
from d in db.CO_LeatherSizeColor_Vs
select new Globals.CuttingOrderDetail
{
cuttingOrderNo = d.orderNo
}
).ToList()
}).ToList();
I converted this to work in LINQPad with the following query, but I can't get anything to show on the lambda pane.
void Main()
{
var p = (from l in CO_Leather_V
select new CuttingOrder
{
cuttingOrderNo = "NOT SET",
reserveSalesOrderNo = "FAKE_SO_NO",
details = (
from d in CO_LeatherSizeColor_V
select new CuttingOrderDetail
{
cuttingOrderNo = d.OrderNo
}
).ToList()
}).ToList();
p.Dump();
}
// Define other methods and classes here
public class CuttingOrder
{
public string cuttingOrderNo { get; set; }
public string reserveSalesOrderNo { get; set; }
public List<CuttingOrderDetail> details { get; set; }
}
public class CuttingOrderDetail
{
public string cuttingOrderNo { get; set; }
public string reserveSalesOrderNo { get; set; }
public string itemCode { get; set; }
public string material { get; set; }
public string color { get; set; }
public string size { get; set; }
public int qty { get; set; }
public float squareFeet { get; set; }
public float squareFeetUsed { get; set; }
}
If anyone knows how to perform the linq query in lambda form or knows why LINQPad is unable to generate the lamda form it would be greatly appreciated.
This should work:
var p = CO_Leather_V.Select(l=> new CuttingOrder
{
cuttingOrderNo = "NOT SET",
reserveSalesOrderNo = "FAKE_SO_NO",
details = CO_LeatherSizeColor_V.Select(d=>new CuttingOrderDetail {cuttingOrderNo = d.OrderNo}).ToList()
}).ToList();
However, CO_LeatherSizeColor_V does not reference l, so you're going to get everything in that table, every time. You might want something like:
details = l.LeatherSizeColor.Select(d=>new CuttingOrderDetail {cuttingOrderNo = d.OrderNo}).ToList()
for that line instead.
I have a parent entity Widget with core members and multiple WidgetTranslation children that have language translated members i.e. Description text available in English, French, German etc.
e.g.
public class Widget
{
public int Id { get; set; }
public string Code { get; set; }
public virtual ICollection<WidgetTranslation> WidgetTranslations { get; set; }
}
public class WidgetTranslation
{
public int WidgetId { get; set; }
public virtual Widget Widget { get; set; }
public int LanguageId { get; set; }
public virtual Language Language { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Summary { get; set; }
}
What is the most efficient method of querying the widget collection, flattening for a given LanguageId & projecting to a TranslatedWidget DTO
public class TranslatedWidget
{
public int Id { get; set; }
public string Code { get; set; }
public int LanguageId { get; set; }
public virtual Language Language { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Summary { get; set; }
}
Given languageId I've started with
DbSet.Select(w => new TranslatedWidget
{
Id = w.Id,
Code = w.Code,
LanguageId = w.LanguageId,
Name = w.WidgetTranslations.First(wt=>wt.LanguageId == languageId).Name,
Description = w.WidgetTranslations.First(wt=>wt.LanguageId == languageId).Description,
Summary = w.WidgetTranslations.First(wt=>wt.LanguageId == languageId).Summary
});
But I've a feeling this is inefficient and won't scale for more properties on WidgetTranslation.
Thanks
Use SelectMany to flatten structures via a single join:
var widgetQuery = from w in dbSet.Widgets
from wt in w.WidgetTranslations
where wt.Language == languageId
select new TranslatedWidget
{
Id = w.Id,
Code = w.Code,
LanguageId = w.LanguageId,
Name = wt.Name,
Description = wt.Description,
Summary = wt.Summary
});
I'm assuming here that you only have a single translation for each widget in a given language.
I would move Name, Description and Summary into a nested class of your DTO...
public class TranslatedWidgetTranslation
{
public string Name { get; set; }
public string Description { get; set; }
public string Summary { get; set; }
}
public class TranslatedWidget
{
public int Id { get; set; }
public string Code { get; set; }
public int LanguageId { get; set; }
public TranslatedWidgetTranslation Translation { get; set; }
}
Then you can project into that class and need First only once which would result in only one TOP(1) subquery in SQL instead of three:
DbSet.Select(w => new TranslatedWidget
{
Id = w.Id,
Code = w.Code,
LanguageId = languageId,
Translation = w.WidgetTranslations
.Where(wt => wt.LanguageId == languageId)
.Select(wt => new TranslatedWidgetTranslation
{
Name = wt.Name,
Description = wt.Description,
Summary = wt.Summary
})
.FirstOrDefault()
});
You must use FirstOrDefault here, First is not supported in a LINQ-to-Entities projection.
If you don't want that nested type you can project into anonymous types first and then convert into your final class, but the code will be a bit longer:
DbSet.Select(w => new
{
Id = w.Id,
Code = w.Code,
LanguageId = languageId,
Translation = w.WidgetTranslations
.Where(wt => wt.LanguageId == languageId)
.Select(wt => new
{
Name = wt.Name,
Description = wt.Description,
Summary = wt.Summary
})
.FirstOrDefault()
})
.AsEnumerable()
.Select(x => new TranslatedWidget
{
Id = x.Id,
Code = x.Code,
LanguageId = x.LanguageId,
Name = x.Translation != null ? x.Translation.Name : null,
Description = x.Translation != null ? x.Translation.Description : null,
Summary = x.Translation != null ? x.Translation.Summary : null
});