Getting property value based on its column attribute value - linq

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?

Related

Updating Dynamic Columns Issue

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.

How to assign value to label in mvc either from model or viewdata

How to assign value to mvc label. If i have value in model then set item.leadowner but if it's empty then assign the viewdata value. This is my label. Here i assigned the value in viewdata and model value but it's in separate label. I need to use in one label for both value.
#Html.Label("lblLeadOwner", Convert.ToString(ViewData["lblLeadOwner"]), new { id = "lblleadowner" })
#Html.Label("lblLeadOwner", item.LeadOwner, new { id = "lblleadowner" })
Try this ,
#if (items.LeadOwner == "")
{#Html.Label("lblvalue",new { value = ViewData[""] })}
else
{ #Html.Label("lblvalue", items.LeadOwner, new { id = "lblleadowner" })}

Linq replace null/empty value with another value

In sql server I create views where I can check for null values and replace them with a default if I want (i.e. ISNULL(PrimaryPhone, 'No Primary #') AS PrimaryPhone. I used a lot of views in my asp.net web forms application, but I am now learning MVC 4 and want to start out right.
I have a model, controller and view set up for my client table. I would like to be able to replace null/empty values with ("Not Entered") or something like that.
I believe this needs to go in the controller, please correct me if I'm wrong.
I saw an example that uses hasvalue, but it is not available through intellisense.
How would I replace empty/null values without using DefaultValue in my model?
Thanks
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = x.emailadd.DefaultIfEmpty("No Email"),....
You can use the ?? operator to set a default value when something is null:
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = x.emailadd ?? "No Email", ...
If you need more control, for example checking for both null and empty, you can also use the ?: operator (also known as the "conditional operator" or "ternary operator"):
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = string.IsNullOrEmpty(x.emailadd) ? "No Email" : x.emailadd, ...

Issue To Select/Show DropDown Selected Value At Edit() In Asp.net MVC 3

I Using Two Table User And Location In User Table I having LocationId And When I'm going to edit The User Form Then I need User With There Exact Location In Drop Down.but i didn't get that this is my code Of Controller:-
LogisticsEntities db = new LogisticsEntities();
RegisterModel Reg = new RegisterModel();
var tempUser = (from c in db.Users select new RegisterModel { _UserId = c.UserID, UserName = c.Name, Code = c.Code, Email = c.Email, Phone = c.Phone, JobRole = c.JobRole, StartDate = c.StartDate, EndDate = c.EndDate, LocationId = c.Location }).SingleOrDefault(x => x._UserId == id);
var varLocation = from Ls in db.Locations select Ls;
ViewData["LocationId"] = new SelectList(varLocation.ToList(), "LocationID", "Location1", "2");
if (tempUser != null)
return View(tempUser);
else
return View();
And In My View I Have code: -
#Html.DropDownList("LocationID", (SelectList)ViewData["LocationId"])
Thanx In Advance..
You are using LocationID as both first parameter of the dropdown and inside ViewData. In order to generate a dropdown you need 2 things: the first argument will be used to generate the name attribute of the dropdown and used to bind the value back and the second argument must represent a collection of SelectListItem that will be used to create the options of the dropdown. So try using a different key for the collection:
ViewData["locations"] = new SelectList(varLocation.ToList(), "LocationID", "Location1", "2");
and then:
#Html.DropDownList("LocationID", (SelectList)ViewData["locations"])

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