Reputation: 7799
I try to write code that will iterate through my DbSet<staffCompetence>
but it doesn't work.
[HttpPost]
public ActionResult Index(StaffWrapper sw, HttpPostedFileBase file)
{
var st = db.staff.Where(s => s.ID.Equals(sw.Id)).FirstOrDefault();
if (st != null)
{
var cvs = TokenBoxExtension.GetSelectedValues<Guid>("StaffCompetenceTokenBox");
UpdateCompetenceLinks(st.ID, cvs);
//Rewrite values...
db.Entry(st).State = EntityState.Modified;
db.SaveChanges();
}
return View(sw);
}
private void UpdateCompetenceLinks(Guid staffId, Guid[] ids)
{
var model = db.staffCompetence;
for (int i = 0; i < ids.Length; ++i)
{
var id = ids[i];
//On line below it crashes
var scs = model.Where(s => s.competenceID.Equals(id)).ToList(); //ToList() for test
if (!scs.Any())
{
}
}
}
It crashes in the if
condition with exception NotSupported
and a message that it can't create System.Object
constant in this context.
What does it mean? And how to fix it?
P.S. I use Russian located debugger, so I can't post a log. ADDED
Исключение типа "System.NotSupportedException" возникло в EntityFramework.SqlServer.dll, но не было обработано в коде пользователя
Дополнительные сведения: Не удалось создать константу с типом "System.Object". В этом контексте поддерживаются только типы-примитивы и типы перечисления.
In English:
The exception of "System.NotSupportedException" type appears in EntityFramework.SqlServer.dll, but it was not handled by the user code.
Details: The constant creation with "System.Object" type failed. In this context type-premitives and iteration types support only.
P.P.S I translated as I can.
Upvotes: 1
Views: 553
Reputation: 628
You codes can be simplified to something like this following:
using (dbPMEntities db = new dbPMEntities())
{
var model = db.staffCompetence;
foreach (Guid id in ids)
{
**var scs = model.FirstOrDefault(s => s.competenceID.HasValue?s.competenceID.CompareTo(id):null); //Do double-check to see whether the competenceID is of a real value……and check firstOrDefault()**
if (scs==null)
{
var item = new staffCompetence();
item.recID = Guid.NewGuid();
item.competenceID = id;
model.Add(item);
}
}
}
Upvotes: 1
Reputation: 3689
You can't compare System.Guid
directly. Do compare using Guid.CompareTo
instead
dbPMEntities db = new dbPMEntities();
var model = db.staffCompetence;
foreach (Guid id in ids)
{
var scs = model.Where(s => s.competenceID.CompareTo(id) > 0);
if (!scs.Any())
{
var item = new staffCompetence();
item.recID = Guid.NewGuid();
item.competenceID = id;
model.Add(item);
}
}
Upvotes: 0