How to access the Entity Framework - c#

I have mapped the database in the edmx file from the database. Now how do I use linq to make a query?
here is an example of my problem
var Found = from o in ??????
What suppose to go in the question marks. How do I find what suppose to go in the question marks. I have tried many tutorials but that do not tell you exactly how to use Linq.

Well, Entity Framework generates an ObjectContext for you. You should know the name of your ObjectContext class.
Then to query using LINQ you can do something line that
using(var context = new NorthwindContext())
{
var query = from p in context.ProductsSet select p;
// then loop through your query instance.
}
The above example is very simple you should have a look at http://thedatafarm.com/blog/ for better tutorials

Related

Connect to Database with Connection String to use LINQ

I have a connection string and I want to use LINQ to query a remote database. In the Microsoft example they use the DataContext class. However the DataContext does not appear in Intellisense. It says that it uses 'System.Data.Linq` but I am not seeing that either. http://msdn.microsoft.com/en-us/library/bb350721(v=vs.110).aspx
Is there a Hello World example for using a connection string and LINQ?
public void SimpleQuery()
{
var connectionString = #"Server=10.1.10.1;database=Mydatabase;uid=myusername;password=mypassword;";
DataContext dc = new DataContext(connectionString);
var q =
from n in dc.table
select n;
Console.WriteLine(n);
}
Well, that is not how it works or at least it is not that simple.
In order to be able to run linq queries against your DB, first you need to map your db tables to dot net classes.
You can do that in various ways, for example you can use Linq to Sql, or Entity framework.
For EF, you need to decide which EF approach you are going to use (Model First,Code First etc.) Then you should configure your settings and create your db context.Take a look at Entity Framework documentation for more details...

Dynamic LINQ to Entities where EntityType is generic

First off, I'm a noob to EF and LINQ and even to a lesser degree, C# in general. Sorry if my question is poorly phrased or just boneheaded.
I have been searching all over for an example of this, but to no avail. I am trying to create a "search framework" that can accept any entity type in my model, and will present the user a UI to do custom searches with.
While there are 10's or maybe 100's of questions here and elsewhere relating to "Dynamic LINQ" or "Dynamic Query," it seems the one thing they all have in common is that the entity type is known at compile time. What if we DON'T know it at compile time? Meaning, the framework will just accept any entity type from the developer and then build the LINQ query up from there.
What I need to do is have that context.Customers be supplied at runtime, and then build up the "Where(s)" using something like PredicateBuilder, most likely PredicateBuilder.
so something like:
var query = from c in context.Customers select c;
would be more like:
var query = from c in AnyContext.AnyEntity select c;
I guess my question is what object can I use hold the arguments AnyContext and AnyEntity in my compiled code so that they can be replaced with a real context and entity at runtime?
I have looked thoroughly at PredicateBuilder and System.Linq.Dynamic examples but they all have the EntityType defined at design time. To me, that's not a dynamic query, just a dynamic predicate.
var query = from c in AnyContext.AnyEntity select c;
This is exactly the same as:
var query = AnyContext.AnyEntity;
In other words, if the context type and Entity Set property are selected by the user, you could just start with something like this:
var query = (IObjectSet<T>) GetObjectSetViaReflection(context, propertyName);
Also, I'm not sure what other versions of Entity Framework have this, but as of .NET 4.5, you can invoke CreateObjectSet to produce the query:
IObjectSet<T> query = context.CreateObjectSet<T>();
// or, if the context has multiple properties with the same type,
// you can specify a name.
IObjectSet<T> query = context.CreateObjectSet<T>(propertyName);

How to query a stored procedure object with Linq

Say I got this situation: I have to filter one of my entities with data which I get from an stored procedure:
var results = from c in db.Customer
join p in db.GetSPResults() on c.Id equals p.Id
select c;
on my Context class I got this:
public ObjectResult<Example> GetSPResults()
{
return (this as IObjectContextAdapter).ObjectContext.ExecuteFunction<Example>("Proc_Example");
}
So far I run into 2 problems:
I get an InvalidOperationException when code strikes the ExcecuteFunction line:
The FunctionImport 'xxx' could not be found in the container 'xxx'.
Assuming you guys can help me to solve that problem, would it be possible to query that way? Using those stored procedure results like a context entity? I think EF won't allow that cause it's not an entity, nor a "Constant Value".
I'm using EF 4.3.
instead of calling your procedure like that by name as string you can import it in your entity model then you can have a type safe / strongly typed method call directly on your DbContext.
basically you need to execute a function import, see here for an example: Using stored procedures with Entity Framework
Update: for POCO / Code first, see here: EF Code-First - Mapping stored procedures

Exception using Linq query with EF Code first on SQL Server table

I have setup EF code first against my DB (specifically, a table called tblExpenseMain).
In my controller I'm trying to pass an instance of my 'ExpenseMain' class over to the view so the details can be presented. Manually creating an instance and passing it works:
ExpenseMain em = new ExpenseMain { Card_Number = "123", UniqueID_ERLineID = "blah", Item_Amount = 500, Item_Expense_Type = "something"};
return View("_Basic");
But trying to query it with LINQ like so gives me an exception:
ExpenseMain model = (from e in db.ExpenseMains
where e.UniqueID_ERLineID == transUniqueID
select e).SingleOrDefault();
It tells me to check the innerexception to find the problem. I surrounded it with a try/catch and the innerexception message was:
e.InnerException.Message = "Invalid object name 'dbo.ExpenseMains'."
Any suggestions on what I'm doing wrong? I was hoping that the linq query would just grab my single instance and go from there. Changing 'Expensemain model' to 'var model' and looking at what the var becomes, confirms it becomes an 'Expensemain' anyway.
Thanks
If your class name is different from the table name, then you have to configure EF to map them. You can use the table attribute and give the table name.
[Table("tblExpenseMain")]
public class ExpenseMain
{
//properties
}
Do you have several data access layers in your sulotion? Could it be that ExpenseMain is an old Entity, not generated from EF. Double check that there are no tblExpenseMain entity aswell or similar.
Hope this helps.
Looks like u have 2 classes here: ExpenseMain and ExpenseMains

How can I use two different data contexts in one LINQ request?

Can anybody help me with next: how can I use two different data contexts in one LINQ request?
using (var db = new DataMapDataContext(Connection))
{
using (var dbAdd = new DataMapDataContext(ConnectionAdd))
{
return (from i in dbAdd.ITEMs
join p in db.U_OTT_PINs on i.ITEMNO equals p.PIN_CODE
where p.PIN_TYPE == Utils.PinItem
select ...
}
}
Is it possible?
UPDATE:
I resolved my issue, but not with different data contexts:
var listPinnedItems = new List<string>();
using (var db = new DataMapDataContext(Connection))
{
listPinnedItems = (from lpi in db.U_OTT_PINs
where lpi.PIN_TYPE == Utils.PinItem
select lpi.PIN_CODE).ToList();
}
using (var dbAdd = new DataMapDataContext(ConnectionAdd))
{
return (from i in dbAdd.ITEMs
where listPinnedItems.Contains(i.ITEMNO)
...
I'm afraid LINQ to SQL is not made for querying across different databases. See below for possible workaround?
http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/3a15002c-704d-49f9-a8cc-0d2bde186e1d
I don't believe so - these two different contexts could be involved in different transactions in the same database, or even talking to completely different database instances. How would it construct SQL to work across the two?
If you could explain what you're trying to do, we may be able to help you more.
It's possible to use two datacontexts, but you can't do database queries across both at the same time. You could however get the data involved in both queries and query the objects using generic linq statements (linq2objects).
This is one of those questions that shouldn't be answered without first asking "What are you trying to achieve?".
Are both datacontexts pointing to the same database or different databases?
If they connect to same database and the only reason why you have two is that you have separated your entities then you can use just one DC to query a table that 'belongs' to another datacontext. Just use GetTable and L2S will resolve the mappings based on class and member attributes.
If they point to different databases on the same server and the login you're connecting to one of the DBs as has rights to read from the second DB you can include the table from one database in a datacontext based on another db by simply adding the database name as a prefix in the .dbml file.

Categories

Resources