我试图删除一行数据,但它不允许我。我正在使用实体框架。玩家可以在一个团队中,但团队可以有很多玩家。但我想要做的就是删除一个不属于团队的玩家,我应该能够毫无问题地删除它,
我正在使用EF5和asp.net 4 webforms
protected void grdSoccerPlayers_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridDataItem item = e.Item as GridDataItem;
Guid strId = new Guid(item.GetDataKeyValue("id").ToString());
player _player = _dal.GetPlayerBYID(strId);
_dal.SoccerEntities.AddToplayers(_player);
_dal.SoccerEntities.DeleteObject(_player);
_dal.SoccerEntities.SaveChanges();
grdSoccerPlayers.DataBind();
grdSoccerPlayers.Rebind();
}
}
使用以下linq语句正在使用网格。
public IQueryable<player> getAllPlayers()
{
var _player = SoccerEntities.players.ToList();
return _player.AsQueryable();
}
然而,这个外键被放置在播放器表中的teamID上,并将其链接到obv teams表。但我应该仍然能够删除一个不应该的球员?当我去删除一个团队但是该代码工作正常但不是当我想删除一个玩家。我怎么能过来这个。
当我删除addtoplayers时,我收到以下错误
System.InvalidOperationException:无法删除该对象,因为在ObjectStateManager中找不到该对象。 at System.Data.Objects.ObjectContext.DeleteObject(Object entity,EntitySet expectedEntitySet)at System.Data.Objects.ObjectContext.DeleteObject(Object entity)at uniteCms.BackDoor.players._default.grdSoccerPlayers_ItemCommand(Object sender,GridCommandEventArgs e)in c :\ new code \ UniteCms \ UniteCms \ UniteCms \ BackDoor \ players \ default.aspx.cs:第83行
然后我尝试使用以下
来解决它Entity Framework Delete Object Problem
但是它出现了以下错误。
Entity Framework Delete Object Problem
System.InvalidOperationException:具有null EntityKey值的对象无法附加到对象上下文。在System.Data.Objects.ObjectContext.Attach(IEntityWithKey实体)的UniteCms.BackDoor.players._default.grdSoccerPlayers_ItemCommand(Object sender,GridCommandEventArgs e)中的c:\ new code \ UniteCms \ UniteCms \ UniteCms \ BackDoor \ players \ default。 aspx.cs:第83行
答案 0 :(得分:1)
Ok For anyone else it seems ef does not like it when unique value is of 00000000-0000-0000-0000-000000000000 as in null or empty guid once I took care of the roge record it appears to delete ok but its not display the fresh data on my grid till i refresh the page.
Code I end up using for anyone else is.
GridDataItem item = e.Item as GridDataItem;
Guid strId = new Guid(item.GetDataKeyValue("id").ToString());
player _player = _dal.GetPlayerBYID(strId);
_dal.SoccerEntities.Attach(_player);
_dal.DeleteObject(_player);
_dal.SaveChanges();
grdSoccerPlayers.DataBind();
grdSoccerPlayers.Rebind();