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
Related
I am attempting to create a compiled query that can be executed on the database side. The idea is to create a reusable function across my code. But EF Core is still saying this query cannot be translated to sql.
Here is the reusable expression
public static class DisplayFilters
{
public static Expression<Func<DisplayItem, bool>> isActiveItem = (x) => x.IsDeleted == false;
}
Here is the EFCore entity call
using df = namespace.DisplayFilters;
...
[HttpGet]
public IActionResult Get()
{
IEnumerable<DisplayItem> xItem = (from a in _context.DisplayItem.AsQueryable()
where df.isActiveItem.Compile()(a)
select a);
return Ok(xItem);
}
I don't think you can embed Expression type expressions in query comprehension syntax, but you can do it in lambda syntax:
IEnumerable<DisplayItem> xItem = _context.DisplayItem
.Where(df.isActiveItem);
I've been working through https://docs.asp.net/en/latest/tutorials/first-mvc-app/ and after getting the tutorial working, I'd like to convert some of the Entity Framework calls to ADO.NET.
I choose the following function:
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
if (movie == null)
{
return NotFound();
}
return View(movie);
}
I've looked at https://msdn.microsoft.com/en-us/library/dw70f090(v=vs.110).aspx and while it makes sense, how can I return the results of the movie table to that movie object that entity does?
there are multiple steps you need to consider. ADO works with datasets so you fire a sql statement like :
SELECT * FROM Movie where ID = #id
this gives you the data in a dataset with 1 row. Then you need to convert that row into an object so you'll need a mapping in between.
If you want to simplify your life you can use a simple ORM like Dapper which allows you to fire the request and then maps the result into an object for you, provided that the fields match.
How can I include a related entity, but only select the top 1?
public EntityFramework.Member Get(string userName)
{
var query = from member in context.Members
.Include(member => member.Renewals)
where member.UserName == userName
select member;
return query.SingleOrDefault();
}
According to MSDN:
"Note that it is not currently possible to filter which related entities are loaded. Include will always bring in all related entities."
http://msdn.microsoft.com/en-us/data/jj574232
There is also a uservoice item for this functionality:
http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015345-allow-filtering-for-include-extension-method
The approach to use an anonymous object works, even though it's not clean as you wish it would be:
public Member GetMember(string username)
{
var result = (from m in db.Members
where m.Username == username
select new
{
Member = m,
FirstRenewal = m.Renewals.FirstOrDefault()
}).AsEnumerable().Select(r => r.Member).FirstOrDefault();
return result;
}
The FirstRenewal property is used just to make EF6 load the first renewal into the Member object. As a result the Member returned from the GetMember() method contains only the first renewal.
This code generates a single Query to the DB, so maybe it's good enough for You.
I'm currently planning on switching my "manual query-writing" code to a nice SQL framework, so I can leave the queries or sql things to the framework, instead of writing the queries myself.
Now I'm wondering how I can get a single record from my table in Entity Framework 4?
I've primarily used SQL like SELECT * FROM {0} WHERE Id = {1}. That doesn't work in EF4, as far as I'm concerned.
Is there a way I can select a single ID-Based record from my Context?
Something like:
public Address GetAddress(int addressId)
{
var result = from Context.Addresses where Address.Id = addressId;
Address adr = result as Address;
return Address;
}
Thank you!
var address = Context.Addresses.First(a => a.Id == addressId);
You can use Single or First methods.
The difference between those methods is that Single expects a single row and throws an exception if it doesn't have a single row.
The usage is the same for both of them
(Based on VS 2015) If you create an .edmx (Add --> ADO.NET Entity Data Model).
Go through the steps to created the ".edmx" and use the following to run the stored procedure. emailAddress is the parameter you are passing to the stored procedure g_getLoginStatus. This will pull the first row into LoginStatus and status is a column in the database:
bool verasity = false;
DBNameEntities db = new DBNameEntities(); // Use name of your DBEntities
var LoginStatus = db.g_getLoginStatus(emailAddress).FirstOrDefault();
if ((LoginStatus != null) && (LoginStatus.status == 1))
{
verasity = true;
}
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