ASP .NET Entity: EntityCommandExecutionException - c#

I'm getting this error when i run my server:
An exception of type
'System.Data.Entity.Core.EntityCommandExecutionException' occurred in
EntityFramework.SqlServer.dll but was not handled in user code
Additional information: An error occurred while executing the command definition. See the inner exception for details.
Here's my ActionResult where this exception occurs, at line in foreach loop. Table bid from database has foreign key constraint to AspNetUser table.
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);
}
Here's detailed error:
I'm really confused, first time seeing this exception, hope someone will help me solve this out.
Thanks in advance!

Is it possible one of the records in the bid variable doesn't have an AspNetUser ID value specified, so the relationship is null? Another workaround is I do sometimes have strange errors like this, where even though the ID is specified, the error still persists. Since you've loaded up all of the related user data into the users variable, you could change the line from:
bidders[i] = bid.AspNetUser.Email; // HERE IS EXCEPTION
To
bidders[i] = users.First(i => i.AspNetUserID == bid.AspNetUserID).Email;
i.AspNetUserID is the AspNetUser's ID field (I don't know what it's called, so replace i.AspNetUserID with the correct value) to the bid table's AspNetUserID field (again, replace with the correct name).
If that fails, the user found is NULL, there is a problem somewhere that needs to be determined; the user isn't linked and coming back, and for that you need to identify the specific record in the bid variable that isn't linked properly...

Related

Insert multiple record into one model with condition ASP.NET MVC

I'm trying to insert multiple record into database with loop, it's really pain for me when insert bills record for each room in used. So my goal is to create bill for all rooms in used TRANGTHAI == 1 by using form.
Here's my controller:
[HttpPost]
public ActionResult Create(HOADON hoadon)
{
if (ModelState.IsValid)
{
dynamic listPhong = (from p in db.PHONGs where p.TRANGTHAI == 1 select p.ID_PHONG).ToList();
foreach (var phong in listPhong)
{
hoadon = new HOADON()
{
ID_PHONG = phong.ID_PHONG, // cant get ID here
ID_DONGIA = 1,
TRANGTHAI = "Chua dong tien" // status = "Not paid"
ID_CANBO = int.Parse(Session["ID"].ToString()) // get ID manager who creates this bill
};
db.HOADONs.Add(hoadon);
return RedirectToAction("Index");
}
db.SaveChanges();
return View(hoadon);
}
I keep the month and year in the Create.cshtml so manager just need to type 2 of them and the rest is auto generated.
If I putID_PHONG = 1 in controller, it works but get the data of current room that has ID_PHONG = 1.
When I put ID_PHONG = phong.ID_PHONG (code suggestion doesn't suggest to me) and run the project, it throws Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''int' does not contain a definition for 'ID_PHONG'' and This exception was originally thrown at this call stack: HoaDon02.Controllers.HOADONsController.Create(HoaDon02.Models.HOADON) in HOADONsController.cs [External Code]
I also tried put these two model into view model (get, set) and call it like this
public ActionResult Create(ViewModel_HoaDon vm)
{
var id_phong = (vm.Phong.ID_PHONG);
if (ModelState.IsValid)
{
dynamic listPhong = (from p in id_phong where p.TRANGTHAI == 1 select p.ID_PHONG).ToList(); // red line in id_phong and where.
foreach (var phong in listPhong)
{
HOADON data = new HOADON()
{
ID_PHONG = phong.ID_PHONG,
ID_DONGIA = 1,
THANG = 1,
NAM = DateTime.Now.Year,
ID_CANBO = int.Parse(Session["ID"].ToString())
};
db.HOADONs.Add(data);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vm);
}
The error it throws is: Could not find an implementation of the query pattern for source type 'int'. 'Where' not found.
Please let me know if you have solutions.
Thanks a lot.
Thanks to Chetan, I have two solution for this. You can use dynamic or List<int>
and in
HOADON data = new HOADON()
{
ID_PHONG = phong.ID_PHONG,
ID_DONGIA = 1,
THANG = 1,
NAM = DateTime.Now.Year,
ID_CANBO = int.Parse(Session["ID"].ToString())
};
you just simplify to ID_PHONG = phong

How to add multiple objects to a foreign table using Entity Framework

I am new to Entity Framework. I have two tables called Polls and Candidates which have a one-to-many relationship.
I want to add multiple candidates to a poll.
This is my code:
public bool InsertPolls(PollModel _polls)
{
polls = new Poll();
candidates = new candidate();
polls.Name = _polls.name;
polls.startDate = startDate;
polls.endDate = endDate;
polls.Type = _polls.pollType;
foreach (var candidatesID in _polls.candidateID)
{
candidates.Person_ID = candidatesID;
candidates.Poll = polls;
_dbContext.candidates.Add(candidates);
_dbContext.SaveChanges();
}
}
But this throws an exception
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code Additional information: The property 'Person_ID' is part of the object's key information and cannot be modified.
Can anyone help me with this?
Thank You!
for remedy this problem put in first line in the for loop flowing code
candidates = new candidate();
also remove candidates = new candidate(); from top of code .
the flowing code in for loop remove too
candidates.Poll = polls;
because you have added in the top of code.
this is the final code
public bool InsertPolls(PollModel _polls)
{
polls = new Poll();
polls.Name = _polls.name;
polls.startDate = startDate;
polls.endDate = endDate;
polls.Type = _polls.pollType;
_dbContext.Polls.Add(polls);
_dbContext.SaveChanges();
foreach (var candidatesID in _polls.candidateID)
{
candidates = new candidate();
candidates.Person_ID = candidatesID;
_dbContext.candidates.Add(candidates);
_dbContext.SaveChanges();
}
}

LINQ C# Null exception

Can anyone explain why I'm sometimes gets a NULL exception on this insert method?
As said is only sometimes, which for me is just even more confusing.
The table OrderLine has a referemce to the table Product in the datacontext (.dbml file)
public void insertNewOrder(string accountNumber, int orderId)
{
var order = orderRep.GetOrderById(orderId);
var orderlineData = orderLineRep.GetOrderLines(order.OrderID);
foreach (var orderLine in orderlineData)
{
int currentStatus = dlvRep.getAxOrderStatusNumber(orderLine.ItemNumber, 0);
string levering = "";
string status = dlvRep.getAxOrderStatus(orderLine.ItemNumber, currentStatus, out levering);
WebsiteOrderStatus insertNew = new WebsiteOrderStatus
{
AccountNumber = accountNumber,
OrderID = orderId,
ItemNumber = orderLine.ItemNumber,
ItemName = orderLine.Product.Name,
FormatName = orderLine.Product.ProductFormatName,
Quantity = orderLine.Quantity,
Price = orderLine.Price,
Status = status,
Levering = levering,
LastUpdatedStatus = currentStatus,
CreatedDate = DateTime.Now
};
db.WebsiteOrderStatus.InsertOnSubmit(insertNew);
db.SubmitChanges();
}
}
Exception message:
Cannot insert the value NULL into column 'FormatName', table 'GWportal.dbo.WebsiteOrderStatus'; column does not allow nulls. INSERT fails.
The statement has been terminated.
When I look up the products which this code is having trouble finding the ProductFormatName for. The value of ProductFormatName is not NULL and it's having the value as I expected ex: "PS3".
Another strange thing is, why aren't it complaining about:
ItemName = orderLine.Product.Name,
This coulmn does not allow nulls either.
It's probably a bug in the code fororderLineRep.GetOrderLines(order.OrderID) that causes orderLine.Product.ProductFormatName to be set to null.
Try adding some debug code:
foreach (var orderLine in orderlineData)
{
if (orderLine.Product.ProductFormatName == null) {
throw new Exception("ProductFormatName == null");
}
// ...
Another strange thing is, why aren't it complaining about:
ItemName = orderLine.Product.Name,
This coulmn does not allow nulls either.
I can think of two explanations:
orderLine.Product.Name isn't null. The bug mentioned above may affect only ProductFormatName.
orderLine.Product.Name is null, but one error is enough to terminate the statement immediately. Only one error will be reported. Other errors that are also present won't be reported until the first error is fixed.

C# Linq is removing a value from my entity

So, in a desperate attempt to wrangle EntityFramework into being usable. I am here..
private MyEntity Update(MyEntity orig)
{
//need a fresh copy so we can attach without adding timestamps
//to every table....
MyEntity ent;
using (var db = new DataContext())
{
ent = db.MyEntities.Single(x => x.Id == orig.Id);
}
//fill a new one with the values of the one we want to save
var cpy = new Payment()
{
//pk
ID = orig.ID,
//foerign key
MethodId = orig.MethodId,
//other fields
Information = orig.Information,
Amount = orig.Amount,
Approved = orig.Approved,
AwardedPoints = orig.AwardedPoints,
DateReceived = orig.DateReceived
};
//attach it
_ctx.MyEntities.Attach(cpy, ent);
//submit the changes
_ctx.SubmitChanges();
}
_ctx is an instance variable for the repository this method is in.
The problem is that when I call SubmitChanges, the value of MethodId in the newly attached copy is sent to the server as 0, when it is in fact not zero if I print it out after the attach but before the submit. I am almost certain that is related to the fact that the field is a foreign key, but I still do not see why Linq would arbitrarily set it to zero when it has a valid value that meets the requirements of the constraint on the foreign key.
What am I missing here?
You should probably set Method = orig.Method, but I can't see your dbml, of course.
I think you need to attach the foreign key reference
var cpy = new Payment()
{
//pk
ID = orig.ID,
//other fields
Information = orig.Information,
Amount = orig.Amount,
Approved = orig.Approved,
AwardedPoints = orig.AwardedPoints,
DateReceived = orig.DateReceived
};
//create stub entity for the Method and Add it.
var method = new Method{MethodId=orig.MethodId)
_ctx.AttachTo("Methods", method);
cpy.Methods.Add(method);
//attach it
_ctx.MyEntities.Attach(cpy, o);
//submit the changes
_ctx.SubmitChanges();

Errors when creating a custom Querable object with MVC and Subsonic pagedlist

hiya, i have the following code but when i try and create a new IQuerable i get an error that the interface cannot be implemented, if i take away the new i get a not implemented exception, have had to jump back and work on some old ASP classic sites for past month and for the life of me i can not wake my brain up into C# mode.
Could you please have a look at below and give me some clues on where i'm going wrong:
The code is to create a list of priceItems, but instead of a categoryID (int) i am going to be showing the name as string.
public ActionResult ViewPriceItems(int? page)
{
var crm = 0;
page = GetPage(page);
// try and create items2
IQueryable<ViewPriceItemsModel> items2 = new IQueryable<ViewPriceItemsModel>();
// the data to be paged,but unmodified
var olditems = PriceItem.All().OrderBy(x => x.PriceItemID);
foreach (var item in olditems)
{
// set category as the name not the ID for easier reading
items2.Concat(new [] {new ViewPriceItemsModel {ID = item.PriceItemID,
Name = item.PriceItem_Name,
Category = PriceCategory.SingleOrDefault(
x => x.PriceCategoryID == item.PriceItem_PriceCategory_ID).PriceCategory_Name,
Display = item.PriceItems_DisplayMethod}});
}
crm = olditems.Count() / MaxResultsPerPage;
ViewData["numtpages"] = crm;
ViewData["curtpage"] = page + 1;
// return a paged result set
return View(new PagedList<ViewPriceItemsModel>(items2, page ?? 0, MaxResultsPerPage));
}
many thanks
you do not need to create items2. remove the line with comment try and create items2. Use the following code. I have not tested this. But I hope this works.
var items2 = (from item in olditems
select new ViewPriceItemsModel
{
ID = item.PriceItemID,
Name = item.PriceItem_Name,
Category = PriceCategory.SingleOrDefault(
x => x.PriceCategoryID == item.PriceItem_PriceCategory_ID).PriceCategory_Name,
Display = item.PriceItems_DisplayMethod
}).AsQueryable();

Categories