I am trying to filter a flattened nested loop and filter from another list. So below is what I have been able to do. I tried this approach but when I run the query it does not save anything in the database. I need help to check and ignore existing records (same MemberId and Description) in the Tasklist table.
var addedtop = from a in db.TaskLists select new {a.MemberId,a.Description};
var membtasks = from m in members
from n in tasks
select new { m, n };
TaskList taskList = new TaskList();
foreach (var item in membtasks)
{
var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m);
if(exist == null)
{
taskList .Description = item.n;
taskList .MemberId = item.m;
db.taskList .Add(taskList );
db.SaveChanges();
}
}
return Redirect(url);
The problem is exists
will never be null
. The line var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m);
returns an IQueryable
that describes your query but hasn't actually executed against the database yet.
Try changing the line to:
var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m).SingleOrDefault();
This executes the query and checks if there is a single item that satisfies your query. If there is no result at all the query returns null
which will execute the code inside your if statement.
Your statement has not been executed query, you can change Where to Any like this:
var exist = db.TaskLists.Any(a => a.Description == item.n && a.MemberId == item.m);
Any
function that returns data type is bool
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.