Entity Framework 4.0 with Linq
public IEnumerable<Models.Comment> GetUserComments()
{
return List<Comment>
{
new Comment
{
CommentFor = "ee",
DateAdded = DateTime.Now,
CommentText = "aaaa",
Location = new Location
{
Name = "Location Name",
Country = new Country
{
Name="Israel"
},
State=new State { Name="TelAviv" }
}
}
};
}
Can you help me correct Linq query for that?
I need to take value from database using Entity Framework 4.
I did like this public IEnumerable<Models.Comment> GetUserComments()
{
var comment = (from u in context.Comments
where u.UserID == userId
select new Comment
{
//Location = context.Locations.FirstOrDefault(x => x.locationid == u.LocationID).name,
Location = (from l in context.Locations
where l.LocationID == u.LocationID
开发者_开发技巧 select new Location
{
Name = l.Name,
State = (
from s in context.States
where (s.StateID == l.StateID)
select new State { Name = s.Name }
).FirstOrDefault()
}
).FirstOrDefault(),
CommentFor = "bs",
DateAdded = u.DateAdded,
CommentText = u.CommentText
}
).ToList();
}
getting error like:
The entity or complex type 'CGWeb.Models.Repositories.Comment' cannot be constructed in a LINQ to Entities query.
Please tell me where my mistake i had done
u.Location
should be Location
.
select new Comment
{
u.Location //<- remove the u.
Try this
var comment = (from u in context.Comments
where u.UserID == userId
select new Comment
{
Location = context.Locations.FirstOrDefault(x=>x.LocationID==u.LocationID).Name,
CommentFor = "Bb",
DateAdded = u.DateAdded,
CommentText = u.CommentText
}
).ToList();
精彩评论