ASP .NET实体:EntityCommandExecutionException

时间:2016-08-22 17:16:17

标签: c# asp.net entity-framework

运行我的服务器时出现此错误:

  

类型的例外   发生'System.Data.Entity.Core.EntityCommandExecutionException'   EntityFramework.SqlServer.dll但未在用户代码中处理        附加信息:执行命令定义时发生错误。有关详细信息,请参阅内部异常。

这是我发生此异常的ActionResult,在foreach循环中的行。来自数据库的表出价对AspNetUser表具有外键约束。

public ActionResult Details(long? id)
{
if (id == null)
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

auction auction = db.auctions.Find(id);

if (User.IsInRole("Administrator"))
    ViewBag.UserRole = "Administrator";
else if (User.IsInRole("User"))
    ViewBag.UserRole = "User";
else
    ViewBag.UserRole = "Guest";

var bids = from b in db.bids
            where b.IDAuc == id
            orderby b.tokens
            descending select b;

var bidsLimited = bids.Take(10);
var users = from b in db.AspNetUsers
            select b;

int count = bidsLimited.Count();
long[] prices = new long[count];
string[] bidders = new string[count];
string[] times = new string[count];
string[] states = new string[count];
int i = 0;

foreach (var bid in bidsLimited)
{
    prices[i] = bid.tokens;
    bidders[i] = bid.AspNetUser.Email; // HERE IS EXCEPTION
    times[i] = bid.created.ToString(@"dd\:hh\:mm\:ss");
    states[i++] = "Open";
}

if (auction.state == "Sold")
    states[0] = "Sold";

ViewBag.count = count;
ViewBag.prices = prices;
ViewBag.bidders = bidders;
ViewBag.times = times;
ViewBag.states = states;
ViewBag.IDAuction = id;

return View(auction);
}

以下是详细错误: enter image description here

我真的很困惑,第一次看到这个例外,希望有人能帮我解决这个问题。

提前致谢!

1 个答案:

答案 0 :(得分:0)

bid变量中的一个记录是否可能没有指定AspNetUser ID值,因此该关系为空?另一种解决方法是我确实有这样的奇怪错误,即使指定了ID,错误仍然存​​在。由于您已将所有相关用户数据加载到users变量中,因此可以更改以下行:

bidders[i] = bid.AspNetUser.Email; // HERE IS EXCEPTION

bidders[i] = users.First(i => i.AspNetUserID == bid.AspNetUserID).Email;

i.AspNetUserID是AspNetUser的ID字段(我不知道它的名称,因此将i.AspNetUserID替换为正确的值)到出价表的AspNetUserID字段(再次,用正确的名称替换)。

如果失败,则发现用户为NULL,某处需要确定问题;用户未链接并返回,为此您需要识别出价变量中未正确链接的特定记录...