I am using Linq to Sql and I need to fetch only the needed fields. This is something that I was able to accomplish using Dynamic Linq. Does anyone know how I can fetch only one or more fields and then add it to my Grid without re query and regenerate the whole object again?? Something similar to Merge method of a dataset but with Linq to SQL?
I hope I understand your question. Does one of these help you?
var List1 = db.myTable.Select(k => new myObject
{
ID = k.Id,
field1 = k.field1
});
var List2 = from k in db.myTable select new myObject()
{
ID = k.Id,
field1 = k.field1
};
else can you provide an example?
Related
(I'm completely new to Linq to SQL) I am creating a web app that works very closely with a database, I'm looking for the quickest and connection time efficient model and believing Linq to SQL to be this. I'm using C#/.Net4/Visual Studio 2010
For simplicity sake, I have a web .aspx page containing a number of asp Text Boxes. I want to give their Text values from SQL data via Linq to SQL object. I also have a file called DataClasses.dbml with a a table added in the design view. The code I have so far in my web page code-behind is:
DataClassesDataContext db = new DataClassesDataContext(getConnectionString);
var table = from t in db.MyTable
where t.PK == 2
select new { t.col1, t.col2, t.col3};
db.Connection.Open();
db. // What's the best way of loading the object?
db.Connection.Close();
How do I then access the column values? Or do I databind it to a datatable? If so, how?
myTextBox1.Text = table.???col1.value;
You don't need to open or close the connection. LinqToSql abstracts that away for you.
Once you created the query, you can execute it and retrieve the row as an object using SingleOrDefault().
using (var db = new DataClassesDataContext(getConnectionString))
{
var query = from t in db.MyTable
where t.PK == 2
select new { t.col1, t.col2, t.col3};
var myObject = query.SingleOrDefault();
}
You can also simplify this operation by using the lambda notation:
using (var db = new DataClassesDataContext(getConnectionString))
{
var myObject = db.MyTable.SingleOrDefault(t => t.PK == 2 )
}
To access the object you can directly access the columns since they have been mapped to the corresponding properties:
myTextBox1.Text = myObject.col1;
Common way is to call method that will execute query (ToArray, ToList, First, Single, etc..) or enumerate it in foreach.
For example:
var query = from t in db.MyTable
where t.PK == 2
select new { t.col1, t.col2, t.col3};
var result = query.ToArray(); // now it contains array of resulting objects
// or enumerate
foreach (var obj in query)
{
// do stuff with obj
}
Use
myTextBox1.Text = table.FirstOrDefault().col1.ToString();
I wrote the following query in LINQ:
memberlist is List of membershipuserwrapper
List<usercodes> testlist = new List<usercodes>();
testlist.Add(new usercodes { usercode = "na02\\srosner" });
testlist.Add(new usercodes { usercode = "Schie#testtest.com" });
var filtered = (from c in memberList
where (from t in testlist
select t.usercode.ToLower())
.Contains(c.UserName.ToLower())
select c)
.ToList();
Now, I have DataTable with a list of users in place of testlist and I want to use that DataTable in place of my LINQ query.
Can I use that how to do that in way of DataTable?
You should be able to use:
from t in testlist.AsEnumerable()
select t.Field<string>("usercode").ToLower()
in place of the original:
from t in testlist
select t.usercode.ToLower()
Personally, though, I'd say that the List<usercodes> is a vast improvement from a DataTable, and would encourage you to pursue the original version (maybe changing the class-name to UserCodes or similar).
I have three tables I'm getting info from: User, Field, FieldUserInput. I already know the userId which is what I use to find out what fields the user has input. Then I want to get the value of those fields that the user has input in FieldUserInput.
I first wrote this query in plain old sql but I want to use LINQ as much as possible since that's why I use Entity Framework.
SELECT fielduserinput.field_idField, fielduserinput.userInput, fielduserinput.time
FROM fielduserinput
WHERE fielduserinput.userId = #userId
Any suggestions as to how I would write this in LINQ?
Considering you have a datasource filled with data.
var matchingRows = from rows in fielduserinput.AsEnumarable()
where string.compare(rows["userId"].ToString(),userID)==0
select rows;
var result = from row in fielduserinput
where row.userId = "???"
select new { row.field_idField, row.userInput, ...};
var response = fielduserinput
.Where(x=>x.userid == #userid)
.Select(x=>new { field_idfieldid = x.field_idfieldid, etc })
.ToList()
Is there a good way of requesting only specified columns from the database using LINQ? I want to be able to select only certain columns depending on arbitrary conditions from code.
You can create anonymous types for each condition, which contain only the columns you specify.
var anonymousType = from item in itemCollection
select new {Column1 = item.Column1, Column2 = item.Column2};
var anonymousType2 = from item in itemCollection
select new {Column2 = item.Column2, Column3 = item.Column3};
Not sure exactly what you mean.
Are you maybe wanting to pull different columns based on a conditional?
Something like this?
if(condition)
{
table.Select(x => x.ColumnA);
}
else
{
table.Select(x => x.ColumnB);
}
Is there a way to use LoadWith but specify the fields that are returned?
For example, if I have two tables 1) Products 2) Categories
and do something like
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Products>(d => d.Categories);
db.LoadOptions = dlo;
MyDataContext db = new MyDataContext();
var result = from d in db.Products
select d;
when i check the query in profiler i see that ALL the rows from the Categories table are being returned. All I really need is the "Name" field.
I know I can rewrite the query using joins but I need to return the result set as a "Product" data type which is why I am using LoadWith.
No that's not possible with LoadWith.
You could try with a nested query in the projection, though that will be slow: 1 query per parent (so 1 query for the related category per product loaded).
You can use a projection, but you need to deal with anynomus types after that
select new {Order = order, ProductName = order.Product.Name,
CustomerName = order.Customer.Name,
OrderType = order.OrderType.Name } // etc