LINQ to ADO.NET Entity Data Modelassign value to object - linq

Can I assign values to user object without looping in query result? I don't need looping there will be only one or no return from the query.
protected user GetUser(user u, string name, string password)
{
using (DBEntities db = new DBEntities())
{
var selectedUser = from p in db.users
where p.name == name && p.pass == password
select p;
if (selectedUser.Count() == 1)
{
foreach (user us in selectedUser)
{
u.id = us.id;
u.name = us.name;
u.pass = us.pass;
}
}
return u;
}
}

I guess you are looking for:
using (var db = new DBEntities())
{
return db.users.SingleOrDefault(u => u.name == name && u.pass == password);
}

Related

i am trying to join 3 tables below is the code

var result = (from p in db.push_notifications
join nu in db.notification_recievers on p.id equals nu.push_notification_id
join nt in db.notification_types on p.notification_type_id equals nt.id
where (p.id == pushNotificationId && p.send_criteria == criteria && nu.delete_flag == false && p.delete_flag == false && nt.delete_flag == false)
select new NotificationList
{
conferenceId = p.conference_id,
pushNotificationId = p.id,
notificationId = nt.id,
notificationType = nt.notification_type,
nottificationDate = p.created_dt_tm,
criteria = (int)p.send_criteria,
notificationMessage = p.notification_msg,
userEmail=null,
userInterests = **getInterestNamesByPushNotificationId(p.id)**,
userEvents=null
}).Distinct();
public string getInterestNamesByPushNotificationId(int id)
{
string interests = string.Empty;
var query = from i in db.interests
join pn in db.notification_recievers
on i.id equals pn.interest_id
where pn.push_notification_id == id && pn.delete_flag == false
select new
{
name = i.name
};
foreach (var intr in query.Distinct())
{
if (interests == "")
{
interests = intr.name;
}
else
{
interests = interests + ", " + intr.name;
}
}
return interests;
}
this is throwing me error
LINQ to Entities does not recognize the method 'System.String
getInterestNamesBy PushNotification(Int32)' method, and this method
cannot be translated into a store expression.
The Entity Framework is trying to execute your LINQ clause on the SQL side, obviously there is no equivalent to 'getInterestNamesBy PushNotification(Int32)' from a SQL perspective.
You need to force your select to an Enumerable and then reselect your object using the desired method.
Not ideal but something like this should work - (not tested this so be nice).
var result = (from p in db.push_notifications
join nu in db.notification_recievers on p.id equals nu.push_notification_id
join nt in db.notification_types on p.notification_type_id equals nt.id
where (p.id == pushNotificationId && p.send_criteria == criteria && nu.delete_flag == false && p.delete_flag == false && nt.delete_flag == false)
select new { p=p, nu = nu, nt = nt }).AsEnumerable().Select( x => new NotificationList()
{
conferenceId = x.p.conference_id,
pushNotificationId = x.p.id,
notificationId = x.nt.id,
notificationType = x.nt.notification_type,
nottificationDate = x.p.created_dt_tm,
criteria = (int)x.p.send_criteria,
notificationMessage = x.p.notification_msg,
userEmail=null,
userInterests = getInterestNamesByPushNotificationId(x.p.id),
userEvents=null
}).Distinct();
i have done it this way
In my model
using (NotificationService nService = new NotificationService())
{
modelView = nService.DetailsOfNotifications(pushNotificationId, criteriaId).Select(x => new NotificationViewModelUI(x.conferenceId, x.pushNotificationId, x.notificationId, x.notificationType, x.nottificationDate, x.criteria, x.notificationMessage, x.userEmail, nService.getInterestNamesByPushNotificationId(x.pushNotificationId), nService.getIEventTitlesByPushNotificationId(x.pushNotificationId))).ToList();
}
public NotificationViewModelUI(int conferenceId, int pushNotificationId, int notificationId, string notificationType, DateTime dateTime, int criteria, string nMessage, string emailId = null, string interestNames = null, string eventTitles = null)
{
this.conferenceId = conferenceId;
this.pushNotificationId = pushNotificationId;
this.notificationId = notificationId;
this.notificationType = notificationType;
this.notificationDate = dateTime;
this.sendCriteria = (NotificationCriteria)criteria;
this.notificationMessage = nMessage;
this.emailId = NotificationCriteria.SpecificUser.Description() +"... "+ emailId;
this.interestNames = NotificationCriteria.UserByInterests.Description() + "... " + interestNames;
this.eventTitles = NotificationCriteria.UserByEvents.Description() + "... " + eventTitles;
}

Comparing objects before and after update retrieved by LINQ query

I am using LINQtoSQL and I need to compare object before and after update.
In the example below Student 'before' and Student 'curStudent' are the same, because they was retrieved by the same query.
using(DataContext db = new DataContext())
{
Student before = db.Student.Where(q=>q.id == 1).SingleOrDefault();
Student curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
curStudent.Name = "NewName";
db.SubmitChanges();
}
if(before.Name != curStudent.Name) // this condition will never be true
{
//do something
}
The context will only keep one object per key value, so one way would be to use two separate contexts:
Student before;
using(DataContext db1 = new DataContext())
{
before = db.Student.Where(q=>q.id == 1).SingleOrDefault();
}
Student curStudent;
using(DataContext db2 = new DataContext())
{
curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
curStudent.Name = "NewName";
db.SubmitChanges();
}
if(before.Name != curStudent.Name)
{
//do something
}
Or if you're just interested in the name change, keep the previous value:
string before;
using(DataContext db = new DataContext())
{
Student curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
before = curStudent.Name; // cache the name
curStudent.Name = "NewName";
db.SubmitChanges();
}
if(before != curStudent.Name)
{
//do something
}

Deep LINQ projections, how?

Let's say I have a model created with EF 4.0
User
Roles
Permissions
Each entity has a DeleteDate property.
I want to get a specific user (with Name =...) and have the tree filled with items where DeletedDate == null..
This must be done with anonymous type projection as result, but I don't know how to accomplish this with a hierachy deeper than 2..
This is what I already have:
public MyProjection MyCall(string givenName)
{
var result = from s in context.Users
where (s.Name == givenName &&
s.DeletedDate == null)
select new
{
s,
roles = from r in s.Roles
where r.DeletedDate == null
select r
};
var outcome = result.FirstOrDefault();
if (outcome != null)
{
var myProjection = new MyProjection()
{
User = outcome.s,
Roles = outcome.roles
};
return myProjection;
}
return null;
}
Depending on your structure you could do something like this:
var result = m.Users.Where(u => u.DeletedDate == null)
.Select( u => new
{
u,
roles = u.Roles.Where(r => r.DeletedDate == null)
.Select(r => new
{
r,
permissions = r.Permissions.Where(p => p.DeletedDate == null)
})
}).FirstOrDefault(item => item.u.Name == givenName);
If you retrieve with the following:
var result = from s in MyUsers
where s.DeletedDate == null
select new aUser{
Roles = (from r in s.Roles
where r.DeletedDate == null
select r).ToList()
};
And then create a TreeView:
TreeView treeView = new TreeView();
Then set the ItemsSource of the TreeView to the IEnumerable:
treeView.ItemsSource = result;
Then build a HierarchicalDataTemplate in your TreeView to represent your Lists (similar to this or for more in depth this), then voila!

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();

save new or update exist record with linq

this is the way i used to save record with linq: (my Q is below)
public void SaveEmployee(Employee employee)
{
using (BizNetDB db = new BizNetDB())
{
BizNet.SqlRep.Data.Employee oldEmployee = (from e in db.Employees
where e.EmployeeID == employee.EmployeeID
select e).SingleOrDefault();
if (oldEmployee == null)
{
oldEmployee = new BizNet.SqlRep.Data.Employee();
oldEmployee.BirthDate = employee.BirthDate;
oldEmployee.WorkRole = employee.WorkRole;
oldEmployee.CurrentFlag = employee.CurrentFlag;
oldEmployee.HireDate = employee.HireDate;
...
db.Employees.InsertOnSubmit(oldEmployee);
}
else
{
if (oldEmployee.BirthDate.Date != employee.BirthDate.Date)
oldEmployee.BirthDate = employee.BirthDate;
if (oldEmployee.CurrentFlag != employee.CurrentFlag)
oldEmployee.CurrentFlag = employee.CurrentFlag;
if (oldEmployee.HireDate.Date != employee.HireDate.Date)
oldEmployee.HireDate = employee.HireDate;
}
oldEmployee.ModifiedDate = DateTime.Now;
db.SubmitChanges();
employee.EmployeeID = oldEmployee.EmployeeID;
}
}
my questions are:
a. are the if statements nesccery? why not to make the assigning without the
check?
mybe the if block take more cpu..
b. why to spearate the new record block and the update block?
when the record is new it will do
db.Employees.InsertOnSubmit(oldEmployee);
and then proceed with the update routine...
The way you're doing it the only reason you need the if statement is to new it up and insert it, so I would use the if statement just for that.
I would do this instead:
public void SaveEmployee(Employee employee)
{
using (BizNetDB db = new BizNetDB())
{
BizNet.SqlRep.Data.Employee oldEmployee =
(from e in db.Employees
where e.EmployeeID == employee.EmployeeID
select e).SingleOrDefault();
if (oldEmployee == null)
{
oldEmployee = new BizNet.SqlRep.Data.Employee();
db.Employees.InsertOnSubmit(oldEmployee);
}
if (oldEmployee.BirthDate.Date != employee.BirthDate.Date)
oldEmployee.BirthDate = employee.BirthDate;
if (oldEmployee.CurrentFlag != employee.CurrentFlag)
oldEmployee.CurrentFlag = employee.CurrentFlag;
if (oldEmployee.HireDate.Date != employee.HireDate.Date)
oldEmployee.HireDate = employee.HireDate;
oldEmployee.ModifiedDate = DateTime.Now;
db.SubmitChanges();
employee.EmployeeID = oldEmployee.EmployeeID;
}
}
I also think there's a way to map one object's properties to the other, but it escapes me at the moment. It may not work for what you're trying to do anyway since it seems that you're doing some other things later anyway with the ModifiedDate and EmployeeID.

Resources