need help
I have this enum which sets the PayClassNo to Direct and Indirect. I want to use this enum in my LinQ query.
Here's my scratch LinQ query:
var jDef = from jd in context.GetTable<RJVDefinition>()
select new PayrollJVDefinition
{
JVdefNo = jd.JVDefNo,
AccntCode = jd.AccntCode,
AccntDesc = jd.AccntDesc,
PayClass = enum.GetValue(jd.PayClassNo),
IsFixed = jd.IsFixed,
IsEmployee = jd.IsFixed,
IsAR = jd.IsAR,
CreatedByNo = jd.CreatedByNo,
CreatedDate = jd.CreatedDate,
ModifiedByNo = jd.ModifiedByNo,
ModifiedDate = jd.ModifiedDate
};
Need help because I'm not sure if this will work.
You could certainly do the translation in code, similar to your example (using Enum.Parse), but you don't need to. You can use the designer to set the object property type to an enumerated value. See this article for details.
You just need to parse the Enum just use something like
Enum.Parse(jb.PayClassNo, YourEnumType)
Related
I try to find some references on LINQ with dynamic added strong types, static I have as in example:
var rowColl = _data.AsEnumerable();
var json = (from r in rowColl
select new
{
name = r.Field<string>("name"),
id = r.Field<int>("id"),
}).ToList();
Now where I am interested in if its possible to make "name" and "id" dynamic added on runtime as the information is available in the DataTable "_data", I think there is a simple solution for this however cant find any references on this
It's better practice to avoid using "var" as your type when possible. It looks like rowColl is of type IEnumerable<DataRow>. If that's true, then I would look to see what you can use in the DataRow class (see msdn documentation).
Given that rowColl is actually IEnumerable<DataRow>... If the columns are always going to be in the same order, then you could just do something like r[0] and r[1] in your select statement, i.e.
var json = (from r in rowColl
select new
{
name = r[0], // Where 0 is the index of the "name" column
id = r[1],
}).ToList();
If it complains at you for type-safety, then you could use int.Parse() to cast the string to an int and use the .ToString() extension on your columns instead.
I am new to linq so please excuse me if I am asking a very basic question:
paymentReceiptViewModel.EntityName = payment.CommitmentPayments.First().Commitment.Entity.GetEntityName();
paymentReceiptViewModel.HofItsId = payment.CommitmentPayments.First().Commitment.Entity.ResponsiblePerson.ItsId;
paymentReceiptViewModel.LocalId = payment.CommitmentPayments.First().Commitment.Entity.LocalEntityId;
paymentReceiptViewModel.EntityAddress = payment.CommitmentPayments.First().Commitment.Entity.Address.ToString();
This code is too repetitive and I am sure there is a better way of writing this.
Thanks in advance for looking this up.
Instead of executing query at each line, get commitment entity once:
var commitment = payment.CommitmentPayments.First().Commitment.Entity;
paymentReceiptViewModel.EntityName = commitment.GetEntityName();
paymentReceiptViewModel.HofItsId = commitment.ResponsiblePerson.ItsId;
paymentReceiptViewModel.LocalId = commitment.LocalEntityId;
paymentReceiptViewModel.EntityAddress = commitment.Address.ToString();
It depends a bit on what you are selecting to, you cannot select from one entity into another in Linq to Entities. If you are using LINQ to SQL and creating the paymentReceiptModel, you can do this.
var paymentReceiptModel = payment.CommitmentPayments.select(x=>new{
EntityName = x.Commitment.Entity.GetEntityName(),
HofItsId = x.Commitment.Entity.ResponsiblePerson.ItsId,
LocalId = x.Commitments.Entity.LocalEntityId,
EntityAddress = x.Commitment.Entity.Address
}).FirstOrDefault();
If you are using an already instantiated paymentReceiptModel and just need to assign properties then you are better looking to the solution by lazyberezovsky.
To get around the limitation in Linq to Entities, if that is what you are using, you could do this
var result = payment.CommitmentPayments.select(x=>x);
var paymentReceiptModel= result.select(x=>new
{
EntityName = x.Commitment.Entity.GetEntityName(),
HofItsId = x.Commitment.Entity.ResponsiblePerson.ItsId,
LocalId = x.Commitments.Entity.LocalEntityId,
EntityAddress = x.Commitment.Entity.Address
}).FirstOrDefault();
This essentially, makes the majority of your query Linq to Objects, only the first line is Linq to Entities
I'm trying to do a Dynamic LINQ like in the ScotGu's blog
var select = db.San_Imovel.Where("Imovel_Id = #0", 123).Select("new(Imovel_Id)");
but I get the error
the best overloaded method match for '.Where(string, System.Data.Objects.OBjectsParameter[])' has some invalid arguments
Are you using .net 3.5?
Note that only 3.5+ supports that syntax.
Use String.Format:
var select = db.San_Imovel.Where(String.Format("Imovel_Id = {0}", 123)).Select("new(Imovel_Id)");
What is that 123 for? In order for this to compile, it will probably need to look like one of these:
var select = db.San_Imovel.Where("Imovel_Id = #0").Select("new(Imovel_Id)");
OR
var select = db.San_Imovel.Where("Imovel_Id = #0 AND SomethingElse = 123").Select("new(Imovel_Id)");
What does var really do in the following case?
var productInfos =
from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
The two lines:
var productInfos = from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
and
IEnumerable<CompilerGeneratedType> productInfos = from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
are equivalent. CompilerGeneratedType is a type that will be created by the compiler and has the three public properties ProductName, Price, and Category. var is helpful for two reasons:
CompilerGeneratedType will be generated by the compiler so it's impossible for you to use the type name in the declaration.
You don't have to think too hard about the collection type of the result. Linq can do its thing and you don't have to worry about it.
var is a placeholder for a compiler-created ("anonymous") type that has three properties, ProductName, Category and Price.
It is NOT a variant (e.g. as in Visual Basic). It is a concrete type and can be used as such in other places in the code.
In this particular case, the type of productInfos is a compiler-generated Anonymous Type with 3 properties, ProductName, Category and Price.
variables with var are implicitly typed local variable which are strongly typed just as if you had declared the type yourself, but the compiler determines the type. it gets the type of the result.
and here a nice read C# Debate: When Should You Use var?
and here another C# 3.0 Tutorial
var = programmer friendly = less typing = makes you lazy(another way of looking at it) = brings obscurity to code if new to 3.5 FW
It eases you from the pain of having to declare the exact type of your query result manually. But I have to empathize, this is not dynamic typing: the productInfos variable will have a static type, but it is created by the compiler instead of you.
I have a combo box in Silverlight. It has a collection of values built out of the properties of one of my LINQ-to-SQL objects (ie Name, Address, Age, etc...). I would like to filter my results based off the value selected in a combo box.
Example: Say I want everyone with a last name "Smith". I'd select 'Last Name' from the drop down list and enter smith into a textbox control. Normally I would write a LINQ query similar to...
var query = from p in collection where p.LastName == textbox.Text select p;
Is it possible to decide the property dynamically, maybe using Reflection? Something like
var query = from p in collection where p.(DropDownValue) == textbox.Text select p;
Assuming:
public class Person
{
public string LastName { get; set; }
}
IQueryable<Person> collection;
your query:
var query =
from p in collection
where p.LastName == textBox.Text
select p;
means the same as:
var query = collection.Where(p => p.LastName == textBox.Text);
which the compiler translates from an extension method to:
var query = Queryable.Where(collection, p => p.LastName == textBox.Text);
The second parameter of Queryable.Where is an Expression<Func<Person, bool>>. The compiler understands the Expression<> type and generates code to build an expression tree representing the lambda:
using System.Linq.Expressions;
var query = Queryable.Where(
collection,
Expression.Lambda<Func<Person, bool>>(
Expression.Equal(
Expression.MakeMemberAccess(
Expression.Parameter(typeof(Person), "p"),
typeof(Person).GetProperty("LastName")),
Expression.MakeMemberAccess(
Expression.Constant(textBox),
typeof(TextBox).GetProperty("Text"))),
Expression.Parameter(typeof(Person), "p"));
That is what the query syntax means.
You are free to call these methods yourself. To change the compared property, replace this:
typeof(Person).GetProperty("LastName")
with:
typeof(Person).GetProperty(dropDown.SelectedValue);
Scott Guthrie has a short series on dyamically built LINQ to SQL queries:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
That's the easy way...then there's another way that's a bit more involved:
http://www.albahari.com/nutshell/predicatebuilder.aspx
You can also use the library I created: http://tomasp.net/blog/dynamic-linq-queries.aspx. You would store the properties in ComboBox as lambda expressions and then just write:
var f = (Expression<Func<Product, string>>)comboBox.SelectedValue;
var query =
from p in collection
where f.Expand(textBox.Text)
select p;