Updating Dynamic Columns Issue - linq

I am trying to update values in table emp. Which column to update is dynamic.
public void updateEmployees(List<String> columnDb, List<String> columnValues)
{
var data = ctx.tblEmployee.Where(e => e.Id == empId).Select(e => e).SingleOrDefault();
....
data.columnDb = columnValues; // Pseudo
ctx.tblEmployee.Add(data);
ctx.SaveChanges();
}
How to update columns which are passed dynamically as a parameter?

You can do this with the power of Reflection.
Just iterate through properties of your object and set the value for the properties that you have in your list.
First, let's build a dictionary with property names and values from your parameters to make the value access easier:
var values = columnDb.Zip(columnValues,
(name, value) => new { Name = name, Value = value })
.ToDictionary(x => x.Name, x => x.Value);
Now, iterate through properties and set values:
var data = ctx.tblEmployee.SingleOrDefault(e => e.Id == empId);
foreach(PropertyInfo property in data.GetType().GetProperties())
{
// Check if property should be updated
if(values.ContainsKey(property.Name))
{
var value = values[property.Name];
// Change the type of the value to the type of the property
object converted = Convert.ChangeType(value, property.PropertyType);
// Set the property value
property.SetValue(data,values[property.Name]);
}
}
Of course, the code above assumes that there is a conversion between string and the type of the properties of your data object.

Related

Replacing empty values with a default value in a Linq to Entities query

In the Linq to Entities query below I need to place a default value in the x.Number in the returned value if the query returns 0 OfficeTelephone objects. I have tried
x.Number??"555-1212" but that throws an error.
from c in Contacts
.Where(a => a.LastName.Contains("ANDUS")).Take(10)
select new
{
Id = c.Id,
OfficeTelephone = c.Telephones.Where(a=>a.TelephoneType.Name.Contains("Office")).Select(x => new { x.AreaCode, x.Number, x.TelephoneType, x.Primary })
}
I've tried something like:
from c in Contacts
.Where(a => a.LastName.Contains("ANDUS")).Take(10)
select new
{
Id = c.Id,
OfficeTelephone = c.Telephones
.Where(a=>a.TelephoneType.Name.Contains("Office"))
.Select(x => new { x.AreaCode, x.Number, x.TelephoneType, x.Primary })
.DefaultIfEmpty()}
But I'm not sure how to push a default object into the DefaultIFEmpty()
Use DefaultIfEmpty and pass a default instance with those value which you would want by default i.e. if no rows are returned.
try it like this:
Contacts.Where(a=>a.LastName.Contains("ANDUS"))
.Take(10)
.Select(x => new
{
Id = x.Id,
OfficeTelephone = x.Telephones
.Where(a=> a.Telephone.Name.Contains("Office"))
.Select(b=> new Telephone
{
b.AreaCode,
b.Number,
b.TelephoneType,
b.Primary
})
.DefaultIfEmpty(new Telephone())
});
where I've assumed that typeof(x.Telephones) == typeof(List<Telephone>)

Complex foreach loop possible to shorten to linq?

I have a cluttery piece of code that I would like to shorten using Linq. It's about the part in the foreach() loop that performs an additional grouping on the result set and builds a nested Dictionary.
Is this possible using a shorter Linq syntax?
var q = from entity in this.Context.Entities
join text in this.Context.Texts on new { ObjectType = 1, ObjectId = entity.EntityId} equals new { ObjectType = text.ObjectType, ObjectId = text.ObjectId}
into texts
select new {entity, texts};
foreach (var result in q)
{
//Can this grouping be performed in the LINQ query above?
var grouped = from tx in result.texts
group tx by tx.Language
into langGroup
select new
{
langGroup.Key,
langGroup
};
//End grouping
var byLanguage = grouped.ToDictionary(x => x.Key, x => x.langGroup.ToDictionary(y => y.PropertyName, y => y.Text));
result.f.Apply(x => x.Texts = byLanguage);
}
return q.Select(x => x.entity);
Sideinfo:
What basically happens is that "texts" for every language and for every property for a certain objecttype (in this case hardcoded 1) are selected and grouped by language. A dictionary of dictionaries is created for every language and then for every property.
Entities have a property called Texts (the dictionary of dictionaries). Apply is a custom extension method which looks like this:
public static T Apply<T>(this T subject, Action<T> action)
{
action(subject);
return subject;
}
isn't this far simpler?
foreach(var entity in Context.Entities)
{
// Create the result dictionary.
entity.Texts = new Dictionary<Language,Dictionary<PropertyName,Text>>();
// loop through each text we want to classify
foreach(var text in Context.Texts.Where(t => t.ObjectType == 1
&& t.ObjectId == entity.ObjectId))
{
var language = text.Language;
var property = text.PropertyName;
// Create the sub-level dictionary, if required
if (!entity.Texts.ContainsKey(language))
entity.Texts[language] = new Dictionary<PropertyName,Text>();
entity.Texts[language][property] = text;
}
}
Sometimes good old foreach loops do the job much better.
Language, PropertyName and Text have no type in your code, so I named my types after the names...

Getting property value based on its column attribute value

List<MyModel1> myModel1 = new List<MyModel1>();
MyUserModel myUserModel = new MyUserModel();
List<MyModel2> myModel2 = new List<MyModel1>();
myModel1 = m_Service1.GetMyModelFields();
myUserModel = m_Service2.GetMyUserDetails();
myModel2 = (from myModel1Field in myModel1
select new MyModel2 { FieldCaption = myModel1Field.FieldAlias,
FieldValue = "" }).ToList<MyModel2>();
myModel1Field.FieldAlias text will be same as value of one of the Column attribute of one of the property in myUserModel. So I have to search for the column atribute(Name) in myUserModel and get the corresponding property values and assign it to 'FieldValue'. If I can't find the value in myUserModel I can set 'FieldValue' as "NA"
One way to get the column attribute(Name) value of for a property is as below when I know the Property name.
myUserModel.GetType().GetProperty("FirstName").GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).Cast<System.Data.Linq.Mapping.ColumnAttribute>().Single().Name
But in my case Property name will not be known. I have to find the property based on the myModel1Field.FieldAlias value. How to go about this. Please suggest.
MyUserModel with one of it's properties
public class MyUserModel {
[Column(Name = "first_name", DbType = "varchar")]
public string FirstName { get; set; }
}
Now if myModel1Field.FieldAlias is 'first_name' then I have to search in MyUserModel for a property with Column attribute(Name) as first_name. If it exists i have to set it's value to 'FieldValue'. Else set 'FieldValue' as "NA".
If you want to get the value of a property and you only know the Name property of one of the ColumnAttribute attributes on it what you can do is this:
// Let's say you have the user model like so:
MyUserModel myUserModel = new MyUserModel { FirstName = "A", LastName = "B"};
// And then you want the value of the property that has the Column attribute Name "first_name"
string searchName = "first_name";
// Using some lambda you can do this (I do not know how to do this in LINQ syntax, sorry)
object propertyValue = typeof (MyUserModel).GetProperties()
.Where(p =>
{
var attrib = (ColumnAttribute)p
.GetCustomAttributes(typeof (ColumnAttribute), false)
.SingleOrDefault();
return (attrib != null &&
attrib.Name.Equals(searchName));
})
.Select(p => p.GetValue(myUserModel, null))
.FirstOrDefault();
if(propertyValue != null)
{
// Do whatever you want with the string "A" here - I suggest casting it to string! :-)
}
Is that what you want?

How to check for null attributes in LinqToXML expressions?

I have a LinqToXML expression where I am trying to select distinct names based on similar attributes. The code is working great and I've put it below:
var q = xmlDoc.Element("AscentCaptureSetup").Element("FieldTypes")
.Descendants("FieldType")
.Select(c => new { width = c.Attribute("Width").Value,
script = c.Attribute("ScriptName").Value,
sqlType = c.Attribute("SqlType").Value,
enableValues = c.Attribute("EnableValues").Value,
scale = c.Attribute("Scale").Value,
forceMatch = c.Attribute("ForceMatch").Value,
forceMatchCaseSensitive = c.Attribute("ForceMatchCaseSensitive").Value,
sortAlphabetically = c.Attribute("SortAlphabetically").Value,
})
.Distinct();
The problem arises since not all the attributes are required, and if one of them is omitted, for example sortAlphabetically, I get an Object not Referenced error. Makes sense, but it there a way to alter the query to only use assign the new values if the attribute actually exists? (Thereby bypassing any null pointer errors)
Instead of using the Value property (which will blow up on a null reference), simply cast the XAttribute to string - you'll either get the value, or a null reference if the XAttribute reference is null. (XElement works the same way, and this applies to all conversions to nullable types.)
So you'd have:
.Select(c => new {
width = (string) c.Attribute("Width"),
script = (string) c.Attribute("ScriptName"),
sqlType = (string) c.Attribute("SqlType"),
enableValues = (string) c.Attribute("EnableValues"),
scale = (string) c.Attribute("Scale"),
forceMatch = (string) c.Attribute("ForceMatch"),
forceMatchCaseSensitive = (string) c.Attribute("ForceMatchCaseSensitive"),
sortAlphabetically = (string) c.Attribute("SortAlphabetically"),
})
Some of those attributes sound like they should actually be cast to int? or bool?, mind you...

Only primitive types ('such as Int32, String, and Guid') are supported in this context when I try updating my viewmodel

I am having some trouble with a linq query I am trying to write.
I am trying to use the repository pattern without to much luck. Basically I have a list of transactions and a 2nd list which contains the description field that maps against a field in my case StoreItemID
public static IList<TransactionViewModel> All()
{
var result = (IList<TransactionViewModel>)HttpContext.Current.Session["Transactions"];
if (result == null)
{
var rewardTypes = BusinessItemRepository.GetItemTypes(StoreID);
HttpContext.Current.Session["Transactions"] =
result =
(from item in new MyEntities().TransactionEntries
select new TransactionViewModel()
{
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID).ItemDescription,
TransactionDate = item.PurchaseDate.Value,
TransactionAmount = item.TransactionAmount.Value,
}).ToList();
}
return result;
}
public static List<BusinessItemViewModel>GetItemTypes(int storeID)
{
var result = (List<BusinessItemViewModel>)HttpContext.Current.Session["ItemTypes"];
if (result == null)
{
HttpContext.Current.Session["ItemTypes"] = result =
(from items in new MyEntities().StoreItems
where items.IsDeleted == false && items.StoreID == storeID
select new BusinessItemViewModel()
{
ItemDescription = items.Description,
StoreID = items.StoreID,
StoreItemID = items.StoreItemID
}).ToList();
}
return result;
However I get this error
Unable to create a constant value of type 'MyMVC.ViewModels.BusinessItemViewModel'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
I know its this line of code as if I comment it out it works ok
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID).ItemDescription,
How can I map ItemDescription against my list of itemTypes?
Any help would be great :)
This line has a problem:
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID)
.ItemDescription,
Since you are using FirstOrDefault you will get null as default value for a reference type if there is no item that satifies the condition, then you'd get an exception when trying to access ItemDescription - either use First() if there always will be at least one match or check and define a default property value for ItemDescription to use if there is none:
ItemDescription = itemTypes.Any(r=>r.StoreItemID==item.StoreItemID)
? itemTypes.First(r=>r.StoreItemID==item.StoreItemID)
.ItemDescription
: "My Default",
If itemTypes is IEnumerable then it can't be used in your query (which is what the error message is telling you), because the query provider doesn't know what to do with it. So assuming the that itemTypes is based on a table in the same db as TransactionEntities, then you can use a join to achieve the same goal:
using (var entities = new MyEntities())
{
HttpContext.Current.Session["Transactions"] = result =
(from item in new entities.TransactionEntries
join itemType in entities.ItemTypes on item.StoreItemID equals itemType.StoreItemID
select new TransactionViewModel()
{
ItemDescription = itemType.ItemDescription,
TransactionDate = item.PurchaseDate.Value,
TransactionAmount = item.TransactionAmount.Value,
CustomerName = rewards.CardID//TODO: Get customer name
}).ToList();
}
I don't know the structure of your database, but hopefully you get the idea.
I had this error due a nullable integer in my LINQ query.
Adding a check within my query it solved my problem.
query with problem:
var x = entities.MyObjects.FirstOrDefault(s => s.Obj_Id.Equals(y.OBJ_ID));
query with problem solved:
var x = entities.MyObjects.FirstOrDefault(s => s.Obj_Id.HasValue && s.Obj_Id.Value.Equals(y.OBJ_ID));

Resources