I'm trying to query a db set, but I can't seem to access the data when I get the results. Here is the code I've tried.
Query #1:
public List<CustomerMain> testing()
{
var context = new CustomerEntities();
var query = context.CustomerMains
.Where(p=> p.FirstName == "Thor")
.Select(p => new CustomerMain {FirstName=p.FirstName,LastName =p.LastName}).ToList();
return query;
}
Query #2:
public IQueryable<CustomerMain> testing()
{
var context = new CustomerEntities();
var query = context.CustomerMains
.Where(p=> p.FirstName == "Thor")
.Select(p => new CustomerMain {FirstName=p.FirstName,LastName =p.LastName});
return query;
}
CustomerMain is my DbSet, If I run either of those and assign the method to a var variable, it gives me no options to grab the FirstName or LastName from the variable. I found I can do it if I convert it to a CustomerMain, but shouldn't the return query be in a CustomerMain type already?
it gives me no options to grab the FirstName or LastName from the variable
Because the method returns a collection or queryable, not a single entity. You need to iterate or select records:
var customers = testing();
foreach (CustomerMain customer in customers)
{
// access customer.FirstName
}
Or:
var customers = testing();
var oneCustomer = customers.FirstOrDefault(c => c.FirstName == "Thor");
// access oneCustomer.FirstName
Or, if you want the method to return one record (or null if none found):
public CustomerMain FindOne(string firstName)
{
using (var context = new CustomerEntities())
{
var query = context.CustomerMains.Where(p => p.FirstName == firstName);
return query.FirstOrDefault();
}
}
Related
I'm trying to make some queries using EF-Core and I have the following code
public List<Visitation> GetAllVisitations()
{
return this.hospital.Visitations
.Where(v => v.DoctorId == this.Doctor.Id)
.Select(v => new Visitation
{
Doctor = v.Doctor,
Patient = v.Patient,
Date = v.Date,
Comments = v.Comments
})
.ToList();
}
public List<Visitation> GetVisitationByPatient(int id)
{
var patient = this.GetPatientById(id);
return this.hospital.Visitations
.Where(v => v.PatientId == patient.Id)
.Select(v => new Visitation
{
Doctor = v.Doctor,
Patient = v.Patient,
Date = v.Date,
Comments = v.Comments
})
.ToList();
}
It is pretty obvious that the Select statement is the same in both methods. However I know that EF Core uses Expression<Func>, rather than Func therefore I do not know how to make an Expression, which can be used in both Select statements.
The query won't execute until you call .ToList(). So you may take the partial query up to the .Where() and pass it to a function that adds the Select() portion.
Something like this:
public List<Visitation> GetAllVisitations()
{
var query = this.hospital.Visitations
.Where(v => v.DoctorId == this.Doctor.Id);
return this.addTransformation(query)
.ToList();
}
public List<Visitation> GetVisitationByPatient(int id)
{
var patient = this.GetPatientById(id);
var query = this.hospital.Visitations
.Where(v => v.PatientId == patient.Id)
return this.addTransformation(query)
.ToList();
}
public IQueriable<Visitation> AddTransformation(IQueriable<Visitation> query)
{
return query.Select(v => new Visitation
{
Doctor = v.Doctor,
Patient = v.Patient,
Date = v.Date,
Comments = v.Comments
});
}
I have a foreach with an ordebydescending(), but in one case I need to use an orderby() instead. Depending on the value of articleType how can I use an inline condition inside the foreach to allow this to happen.
This is the condition I need to build into to determine the use of orderbydescending or orderby
if (articleType == BusinessLogic.ArticleType.Webinar)
This is the full function
public static List<Article> GetArticles(BusinessLogic.ArticleType articleType, long languageID)
{
List<Article> articles = new List<Article>();
using (var db = new DatabaseConnection())
{
foreach (var record in db
.GetArticles(BusinessLogic.SystemComponentID, (int) articleType, languageID)
.OrderByDescending(c => c.Date_Time))
{
#region articleTextLanguageID
long articleTextLanguageID = GetArticleTextLanguageID(record.ID, languageID);
string previewImageName = GetArticle(record.ID, articleTextLanguageID).PreviewImageName;
#endregion
Article article = new Article()
{
ID = record.ID,
Title = record.Title,
Summary = record.Summary,
PreviewImageName = previewImageName,
Date = record.Date_Time,
ArticleTextLanguageID = articleTextLanguageID
};
articles.Add(article);
}
}
return articles;
}
Was thinking something along these lines, but its not working
foreach (var record in db
.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID)
.Where(articleType == BusinessLogic.ArticleType.Webinar.ToString()?.OrderByDescending(c => c.Date_Time)) : .OrderBy(c => c.Date_Time)))
The way to do this would be to construct the query in pieces. For example:
var query = db.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID);
if(articleType == BusinessLogic.ArticleType.Webinar)
{
query = query.OrderByDescending(c => c.Date_Time);
}
else
{
query = query.OrderBy(c => c.Date_Time);
}
foreach(var record in query)
{
// process
}
If you required additional sorting, you'd need an extra variable typed as IOrderedEnumerable/IOrderedQueryable (depending on what GetArticles returns) as an intermediate to chain ThenBy/ThemByDescending:
var source = db.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID);
IOrderedEnumerable<Article> query;
if(articleType == BusinessLogic.ArticleType.Webinar)
{
query = source.OrderByDescending(c => c.Date_Time);
}
else
{
query = source.OrderBy(c => c.Date_Time);
}
if(somethingElse)
{
query = query.ThenBy(c => c.OtherProperty);
}
foreach(var record in query)
{
// process
}
Based on your comment below, as notes above the second example would look more like the following (this means that db.GetArticles returns an IQueryable<Article> and not an IEnumerable<Article>):
var source = db.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID);
IOrderedQueryable<Article> query;
if(articleType == BusinessLogic.ArticleType.Webinar)
{
query = source.OrderByDescending(c => c.Date_Time);
}
else
{
query = source.OrderBy(c => c.Date_Time);
}
if(somethingElse)
query = query.ThenBy(c => c.OtherProperty);
foreach(var record in query)
{
// process
}
You could also shorten it to the following:
var source = db.GetArticles(BusinessLogic.SystemComponentID, (int)articleType, languageID);
var query = articleType == BusinessLogic.ArticleType.Webinar
? source.OrderByDescending(c => c.Date_Time)
: source.OrderBy(c => c.Date_Time);
if(somethingElse)
query = query.ThenBy(c => c.OtherProperty);
foreach(var record in query)
{
// process
}
I'm beginner in web service and want to write web service return linq to sql query result,write this code:
DataClasses1DataContext behzad = new DataClasses1DataContext(conn);
string result;
var query = (from p in behzad.CDRTABLEs
where p.name == "behzad".Trim()
select p).Take(1);
return query.ToString();
but return to me this:
but i want return table data not linq to sql query,how can i solve that?
when i change return query.ToString(); to return query; i get this error:
If you want to return the object of the result you need to create a class and then return it. So first create a class like this:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
And then do the query like this:
var behzad = new DataClasses1DataContext(conn);
var query = (from p in behzad.CDRTABLEs
where p.name == "behzad".Trim()
select new Foo
{
Id=p.Id,
Name=p.Name
}).FirstOrDefault();
return query;
You're ToString-ing the query, rather than the result. Since you are using Take to get one result, you can use FirstOrDefault to evaluate the query and return the first result, or NULL if there isn't any.
var result = (from p in behzad.CDRTABLEs
where p.name == "behzad".Trim()
select p).FirstOrDefault();
return result;
Try to execute your query - call FirstOrDefault():
var query = (from p in behzad.CDRTABLEs
where p.name == "behzad".Trim()
select p).FirstOrDefault()
I'm writing a method to let the client decide which fields they want to select from a table
here is what i do so far
public IList<User> List(int? roleId, int? sequence, string name,System.Linq.Expressions.Expression<Func<User, dynamic>> selector)
{
var query = context.Users.AsQueryable();
if (roleId.HasValue && roleId.Value > 0)
query = query.Where(x => x.RoleId == roleId);
if (sequence.HasValue && sequence.Value > 0)
query = query.Where(x => x.Sequence == sequence);
if (!string.IsNullOrEmpty(name))
query = query.Where(x => x.Name.Contains(name));
query = query.OrderBy(x => x.UserId);
var result = query.Select(selector).ToList();
var users = new List<User>();
User user = null;
foreach (var item in result)
{
user=new User();
user.UserId = item.id;
user.Name = item.name;
//user.Email = item.email;
//user.Sequence = item.sequence;
users.Add(user);
}
return users;
}
it compile an error says: item.id is not define, but i can see item{id=4,name="sam"....}
If you want to give ability for client code to choose, what fields it wants to retrieve from database, then why do you restrict return type to User?
Let the client code choose, which return type it should use:
public IList<T> List(int? roleId, int? sequence, string name,System.Linq.Expressions.Expression<Func<User, T>> selector)
{
// ...
query = query.OrderBy(x => x.UserId);
return query.Select(selector).ToList();
}
Otherwise, I can't imagine, how are you going to convert anything, returned from selector, into User instances.
I have a bunch of Linq to Entity methods that had the same select statement, so I thought I would be clever and separate that out into it's own method to reduce redundancy... but when i attempted to run the code, i got the following error...
this method cannot be translated into
a store expression
Here is the method i created...
public User GetUser(DbUser user, long uid)
{
return new User
{
Uid = user.uid,
FirstName = user.first_name,
LastName = user.last_name
};
}
And am calling in a method like this...
public User GetUser(long uid)
{
using (var entities = new myEntities()) {
return
entities.DbUsers.Where( x => x.uid == uid && x.account_status == ( short )AccountStatus.Active ).
Select( x => GetUser( x, uid ) ).FirstOrDefault( );
}
}
UPDATE: here is the code that works inline
public User GetUser(long uid, long uid_user)
{
using (var entities = new myEntities())
{
var q = from u in entities.DbUsers
where u.uid == uid_user
select new User
{
Uid = u.uid,
FirstName = u.first_name,
LastName = u.last_name,
BigPicUrl = u.pic_big,
Birthday = u.birthday,
SmallPicUrl = u.pic_small,
SquarePicUrl = u.pic_square,
Locale = u.locale.Trim(),
IsFavorite = u.FavoriteFriends1.Any(x => x.uid == uid),
FavoriteFriendCount = u.FavoriteFriends.Count,
LastWishlistUpdate = u.WishListItems.OrderByDescending(x => x.added).FirstOrDefault().added,
Sex = (UserSex)u.sex
};
var user = q.FirstOrDefault();
user.DaysUntilBirthday = user.Birthday.DaysUntilBirthday();
return user;
}
}
The error is spot on, you can't translate that into a T-SQL (or P-SQL) query.
You need to make sure you've executed the query before you attempt to hydrate it into some other type.
Keep it simple, use an extension method. That's what they are there for.
public static User ToUserEntity(this DbUser user)
{
return new User
{
Uid = user.uid,
FirstName = user.first_name,
LastName = user.last_name
};
}
Then in your DAL:
public User GetUser(long uid)
{
User dbUser;
using (var entities = new myEntities())
{
dbUser = entities.DbUsers
.Where( x => x.uid == uid && x.account_status == (short)AccountStatus.Active )
.FirstOrDefault(); // query executed against DB
}
return dbUser.ToUserEntity();
}
See how i hydrate the POCO into an object after the context has been disposed? This way, you ensure EF has finished it's expression work before you attempt to hydrate into a custom object.
Also i dont know why you're passing uid to that method, it's not even being used.
On a further note, you shouldn't need to do this kind of thing (project EF POCO's into your own objects).
If you do, it's a good case for custom POCO's (map the tables straight into your custom POCO's, don't use the Code Generation).
This expression will work to give the desired result (somewhat) I still havent figured out how to pass in additional variables in teh select statements...
..... .Select(GetUser).FirstOrDefault()
static readonly Expression<Func<DbUser, User>> GetUser = (g) => new User {
Uid = g.uid,
FirstName = g.first_name,
LastName = g.last_name,
BigPicUrl = g.pic_big,
Birthday = g.birthday,
SmallPicUrl = g.pic_small,
SquarePicUrl = g.pic_square,
Locale = g.locale.Trim(),
//IsFavorite = g.FavoriteFriends1.Any(x=>x.uid==uid),
FavoriteFriendCount = g.FavoriteFriends.Count,
LastWishlistUpdate = g.WishListItems.OrderByDescending( x=>x.added ).FirstOrDefault().added
};
You can't do this because the getUser method cannot be converted to any TSQL statement.
if you return your DBUser first and then use it as the first parameter of the GetUser method then you are forcing it to execute and once you have you DBUser you can pass it to GetUser
Maybe you can try this:
public User GetUser(long uid)
{
using (var entities = new myEntities())
{
return GetUser(
entities.DbUsers
.Where( x => x.uid == uid && x.account_status == (short)AccountStatus.Active )
.FirstOrDefault(),
uid);
}
}
EDIT
Since you are saying it still fails could it be beacuse of the enum??
public User GetUser(long uid)
{
using (var entities = new myEntities())
{
short status = (short)AccountStatus.Active;
return GetUser(
entities.DbUsers
.Where( x => x.uid == uid && x.account_status == status )
.FirstOrDefault(),
uid);
}
}