Reputation: 16561
I have tens of different views and on some, the data that comes from database, must be manipulated before shown to user.
for example:
var students = _repository.Students.Select(c => { c.StartDate = FixDateToCurrentYear(c.StartDate ); c.EndDate = FixDateToCurrentYear(c.EndDate); return c; }).ToList();
So basically I now have a variable, where Students
StartDate
and EndDate
have been fixed by some logic, which is not relevant at the moment.
The problem here is that, whenever somewhere a SaveChanges() function is called, then the changed dates for students are also persisted to database.
I only want to use the changed dates for the logic in specific view. How could I handle this?
I have heard about .AsNoTracking();
but this must be put directly to DbSet item, but I want to handle it on controller side, is it possible?
Upvotes: 4
Views: 1364
Reputation: 7817
Pull the students from the db first and the do a select to an anonymous type. EF won't know how to track changes on that.
var students =
_repository.Students.ToList()
.Select(s =>
new { StartDate = FixDateToCurrentYear(c.StartDate),
EndDate = FixDateToCurrentYear(c.EndDate),
Student = s });
Upvotes: 4
Reputation: 7215
The quickest thing I can think of is to perform your fix at the point you display it to the user, e.g. in Razor:
@FixDateToCurrentYear(student.StartDate)
In this way, you're not actually changing the value, you're just changing how it's displayed.
If you need to do more than display, you will need to create a partial buddy class, add a new property and modify its get method:
public partial class Student
{
DateTime StartDateComputed {
get
{
return FixDateToCurrentYear(StartDate);
}
set;
}
}
Now, use StartDateComputed instead of StartDate and the same for EndDate.
Upvotes: 0