Simple question - where is dbContext.CreateQuery method in Entity Framework 6 and if the answer is there is not such method my question is what to do to get some data by SQL query to an objectQuery?
Cast context to IObjectContextAdapter and use ObjectContext, e.g.:
using (var context = new AdventureEntities())
{
string eSql = "SELECT VALUE c FROM AdventureEntities.Customer AS c ORDER BY c.LastName";
var query = ((IObjectContextAdapter)context).ObjectContext.CreateQuery<Customer>(eSql);
var customers = query.ToList();
foreach (Customer customer in customers)
{
Console.WriteLine("{0}, {1}", customer.FirstName, customer.LastName);
}
}
Related
I had experience in developing reports(SSRS) using ado.net dataset. Now I am working on an application which is not using ADO.net but entity framework but entity framework does not return datatable or dataset. I want to know
Is there any way to use Collection or custom objects return by entity framework in the reporting services?
Entity framework somehow return datatable or dataset.
Or I should create datatable/dataset from the collection returned by entity framework manually.
For the record, I am getting resultset by executing stored procedure from entity framework.
public void getMyReportData()
{
using (myEntityDataModel v = new myEntityDataModel())
{
var reportQuery = (from r in v.myTable
select new
{
l.ID,
l.LeaveApplicationDate,
l.EmployeeNumber,
l.EmployeeName,
l.StartDate,
l.Col1,
l.Col2,
.......,
.......,
l.Address
}).ToList();
reportViewer1.LocalReport.DataSources.Clear();
ReportDataSource datasource = new ReportDataSource("nameOfReportDataset", reportQuery);
reportViewer1.LocalReport.DataSources.Add(datasource);
Stream rpt = loadEmbededReportDefinition("Report1.rdlc");
reportViewer1.LocalReport.LoadReportDefinition(rpt);
reportViewer1.RefreshReport();
//Another way of setting the reportViewer report source
string exeFolder = Path.GetDirectoryName(Application.ExecutablePath);
string reportPath = Path.Combine(exeFolder, #"rdlcReports\Report1.rdlc");
reportViewer1.LocalReport.ReportPath = reportPath;
reportParameter p = new ReportParameter("DeptID", deptID.ToString());
reportViewer1.LocalReport.SetParameters(new[] { p });
}
}
public static Stream loadEmbededReportDefinition(string reportName)
{
Assembly _assembly = Assembly.GetExecutingAssembly();
Stream _reportStream = _assembly.GetManifestResourceStream("ProjectNamespace.rdlcReportsFolder." + reportName);
return _reportStream;
}
Original source: Creating Reports in ASP.Net with Entity Framework
Study this a moment: Consider a schema with a Person, GovernmentId, and GovernmentIdType tables. Andrew Tappert (Person) has two id cards (GovernmentId), one from Oregon (GovernmentIdType) and one from Washington (GovernmentIdType).
Now generate an edmx from it.
Now imagine you want to find all the people having a certain ID value, say 1234567.
This can be accomplished with a single database hit with this:
dbContext context = new dbContext();
string idValue = "1234567";
Expression<Func<Person,bool>> expr =
person => person.GovernmentID.Any(gid => gid.gi_value.Contains(idValue));
IEnumerable<Person> people = context.Person.AsQueryable().Where(expr);
List<Person> people = peopleQuery.ToList();
This works. Now why does the following result in this closure type exception...
dbContext context = new dbContext();
string idValue = "1234567";
Expression<Func<GovernmentId, bool>> gidExpr = gid => gid.gi_value.Contains(idValue);
Expression<Func<Person,bool>> expr =
person => person.GovernmentID.AsQueryable().Any(gidExpr);
IEnumerable<Person> peopleQuery = context.Person.AsQueryable().Where(expr);
List<Person> people = peopleQuery.ToList();
Edit
Used version is EF 1 (.NET 3.5).
I cannot explain exactly why the second code doesn't work. But apparently there is a problem with using Compile() in this LINQ to Entities query. When testing the code I hadn't your exception but instead an "Internal .NET Framework Data provider error 1025".
The following though did work for me (applying AsQueryable to the GovernmentID collection so that you can use the expression directly without Compile()):
dbContext context = new dbContext();
string idValue = "1234567";
Expression<Func<GovernmentId, bool>> gidExpr =
gid => gid.gi_value.Contains(idValue);
Expression<Func<Person,bool>> expr =
person => person.GovernmentID.AsQueryable().Any(gidExpr);
IEnumerable<Person> people = context.Person.AsQueryable().Where(expr);
The AsQueryable() in the last line is redundant and can be removed since context.Person is an IQueryable<T> anyway.
Edit
Error reproduced with EF 1 (.NET 3.5). With EF 4.0 and EF 4.1 (.NET 4) it works.
I'm using Entity Framework 4.0.
Custumer is an Entity in my ObjectContext, and the Enity class is autogenerated. I get the customers like this:
Public Function GetAll(ByVal companyId As String) As System.Collections.Generic.IEnumerable(Of Customer) Implements ICustomerRepository.GetAll
Return Me.objectSet.Where(Function(p) p.CompId = >companyId).AsEnumerable
End Function
My function returns the reult set correct, but it does not select out only the customers where Comp.Id = conmpanyId. I have also tried
Return From p In Me.objectSet Where p.CompId = companyId Select p
How can I write the query correct?
I really don't know the syntax of VB but try this:
Return Me.objectSet.Where(Function(p) p => p.CompId == companyId).AsEnumerable
i got this error...
LINQ to Entities does not recognize the method 'Int64 GetPostsCountQuery(Int64)' method, and this method cannot be translated into a store expression.
here my code:
private Blog GetBlogDetailsByUserId(long userId)
{
return (from gs in _entities.wu_Blog_General_Settings
//join p in _entities.wu_Blog_Post on gs.User_Id equals p.User_Id
let pCount = GetPostsCountQuery(userId)
let lastPublish = GetPostsLastPublishedQuery(userId, pCount)
where gs.User_Id == userId && !gs.Is_Deleted
select new Blog
{
BlogOwnerUserId = userId,
BlogTitle = gs.Blog_Title,
BlogDescription = gs.Blog_Description,
PostsCount = pCount,
LastPublishedDate = lastPublish
}).SingleOrDefault();
}
#endregion
#region Get Posts Count Query
private long GetPostsCountQuery(long userId)
{
return (from p in _entities.wu_Blog_Post
where p.User_Id == userId && p.Post_State != (int)PostState.Removed &&
!p.Is_Deleted
select p).Count();
}
#endregion
You cannot use .NET method in Linq-to-entities because EF is not able to translate them to SQL (the provider doesn't explore their content).
The only .NET method allowed in linq-to-entities are either:
Connonical methods translated to SQL by EF automatically
Mapped SQL functions or custom SQL operations
Model defined functions
some extension methods running on IQueryable and returning IQueryable
Recently I started porting ADO.net app to Entity Framework. There are some optional columns in my table. With the ADO.net, I just check for existence of the column and get the value if it is there.
if (MyTable.Columns.Contains("PerformPreCheck") &&
DBNull.Value != MyRow[MyTable.Columns["PerformPreCheck"]])
{
m_bPerformPreCheck = (bool)MyRow[MyTable.Columns["PerformPreCheck"]];
}
How can I achieve the same thing with Entity Framework?
Thank you,
Suresh
Presuming your entity is called Foo and the nullable column is called PerformPreCheck:
using(var context = new MyEntities())
{
var f = context.Foos.First(); // or context.Foos.Where(foo => foo.Id == someId).First(), etc....
m_bPerformPreCheck = f.PerformPreCheck.GetValueOrDefault();
}