我正在尝试从ASP.NET MVC中的选定表中删除记录。
所以这是我的行动:
public JsonResult DeleteFromTable()
{
int IDtoDelete = Convert.ToInt32(Request.Form["itemId"]);
string MyTableName = Convert.ToString(Request.Form["TblName"]);
bool results = false;
try
{
using (EBContext db = new EBContext())
{
Type tableType = typeof(CourseDesc);
switch (MyTableName)
{
case "CourseTbl":
break;
case "CourseDescTbl":
tableType = typeof(CourseDesc);
break;
case "CourseSubDesc":
tableType = typeof(CourseSubDesc);
break;
case "InternTbl":
tableType = typeof(InternShip);
break;
case "ContactTbl":
Contact cn = db.Contacts.Where(x => x.ID == IDtoDelete); //This line here is throwing error
bool bcn = UtilityMethods<Contact, int>.InsertEntity(db, cn);
break;
}
return new JsonResult { Data = "results", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
catch (Exception ex)
{
string innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : "";
return new JsonResult { Data = "Not Found", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
我创建了一个类,我传递这些参数并调用我的函数:
internal class UtilityMethods<TEntity, Tid> where TEntity : class
{
public static bool DeleteEntity(EBContext dbContext, TEntity entity)
{
try
{
dbContext.Entry(entity).State = EntityState.Deleted;
dbContext.Set<TEntity>().Remove(entity);
dbContext.SaveChanges();
return true;
}
catch (Exception ex)
{
string abc = ex.Message;
return false;
}
}
}
但我收到错误:
无法将Type'Linq.IQueryable'隐式转换为'EBazar.Models.Contact'。存在显式转换(您是否错过了演员?)
答案 0 :(得分:0)
您可能需要将Where
部分更改为FirstOrDefault
,以使第一个对象具有该条件(如果它存在)。
FirstOrDefault
返回类型的默认值。对于null的引用类型。所以你必须先检查是否为空。
答案 1 :(得分:0)
而不是
Contact cn = db.Contacts.Where(x => x.ID == IDtoDelete);
写
Contact cn = db.Contacts.FirstOrDefault(x => x.ID == IDtoDelete);