entity framework error in .net - c#

I am trying make a join in entity framework and display datas in a label but i get an error like "FileLoadException was unhandled by user code".Here is my codebehind:
protected void display() {
AspNetOrnekEntities entity = new AspNetOrnekEntities();
var everything = (from insan in entity.insanlar
join renk in entity.renkler on insan.SevdigiRenk equals renk.Renk
select new
{
kisiId = insan.KisiId,
renkId = renk.RenkId
});
foreach (var data in everything)
{
Label1.Text += data.kisiId + " " + data.renkId + "<br/>";
}
}
I call "display" in page_load and error comes from that line. I think problem occurs because of first line of the display method because I turned all other lines into comments and problem still occurs. I am using Model1.edmx as connection.

update the EF using the Package manager Console

Related

cannot convert from 'P.CoffeeShopDBEntities' to 'System.Data.Objects.ObjectContext'

I tried to recreate a code (that I've seen in a video) in Visual Studio 2013 (c#) that was written in VS2008 (c#):
I've tried both EF 6 and EF 5 version options same result..searched web and MSDN with no luck.
Here is my code with comments showing the errors I got:
private CoffeeShopDBEntities cse = new CoffeeShopDBEntities();
private void AddProductsToTabbedPanel()
{
// using (CoffeeShopDBEntities context = new CoffeeShopDBEntities())
//--found this on msdn..got rid of old but end up w/2 new errors see below
{
//the foreach code below goes here
}
foreach(TabPage tp in tabControl1.TabPages)
{
ObjectQuery<tblProduct> filteredProduct = new ObjectQuery<tblProduct>
("SELECT VALUE P FROM tblProducts AS P", cse);
//when 'context' used 1)possible mistaken empty statment
//2)the name 'context' doesnt exist in the current context
//when 'cse'used :
//Error 1 The best overloaded method match for 'System.Data.Objects.ObjectQuery<P.tblProduct>.ObjectQuery(string, System.Data.Objects.ObjectContext)' has some invalid arguments
//Error 2 Argument 2: cannot convert from 'P.CoffeeShopDBEntities' to 'System.Data.Objects.ObjectContext'
foreach (tblProduct tprod in filteredProduct)
{
Button b = new Button();
b.Text = tprod.Description;
tp.Controls.Add(b);
}
}
}
I found a similar issue on Stack Overflow and the reply states it's a syntax error but doesn't point out where.
You are getting errors because ObjectQuery is looking for an ObjectContext which comes with EF 4.0 and below. The CoffeeShopDBEntities is of the DBContext type which comes with anything EF 4.1 and above.
I would suggest changing your query to:
List<tblProduct> filteredProducts = cse.tblProducts.ToList();
If you want to read more on the ObjectContext vs. DBContext, you can check out this link:
http://www.c-sharpcorner.com/UploadFile/ff2f08/objectcontext-vs-dbcontext/

Webforms response.redirect returns correct URL and reloads same page

I do some execution when a button is pressed on my webform, inserting an item into my db and storing some info into the session. At the end of that execution the form is supposed to redirect to the next page, but instead it reloads the same page with the URL altered. I have tried to change it from Response.Redirect("URL") to Server.TransferRequest and it still does the same thing. Code is as follows:
protected void CheckoutConfirm_Click(object sender, EventArgs e)
{
//some irrelevant code
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
placedOrder.totalPrice = usersShoppingCart.GetTotal();
_db.Orders.Add(placedOrder);
_db.SaveChanges();
List<CartItem> itemsInCart = usersShoppingCart.GetCartItems();
//creating corresponding OrderProducts for each product in this order
foreach (CartItem o in itemsInCart)
{
Orderproducts myOrderProduct = new Orderproducts();
myOrderProduct.ProductID = o.ProductId;
myOrderProduct.OrderID = placedOrder.OrderID;
myOrderProduct.quantity = o.Quantity;
_db.OrderProducts.Add(myOrderProduct);
_db.SaveChanges();
Session.Clear();
Session["CustomerName"] = customer.CustomerName;
Session["orderID"] = placedOrder.OrderID;
Session["orderStatus"] = placedOrder.OrderStatus;
Session["Address"] = customer.CustomerName + "\r\n" + customer.Address + "\r\n" + customer.City + "\r\n" + customer.Country;
}
}
Server.TransferRequest("Checkout/finishedCheckout.aspx");
Problem was an null reference exception which occurred in the Page_PreRender within the master page. Due to the exception the redirect would not finish and the same page would just reload.

Entity wont delete from Azure Table

when i try to delete the entity Visual Studio keeps crashing on the line "serviceContext.DeleteObject(entity);"and saying "The context is not currently tracking the entity." Has anyone any ideas why and how to fix it?
CloudTableQuery<ScheduleEntity> query = scheduleManNot.retrieveSchedule();
//Checks every entry
foreach (ScheduleEntity entity in query)
{
comparison = System.DateTime.Compare(entity.eventTime, time);
if (comparison <= 0)
{
changeConfirmation = scheduleManNot.changeInstanceCount(entity.subscriptionID, entity.amount, entity.serviceName);
if (changeConfirmation == false)
{
Console.WriteLine("Configuration Change failed");
}
if (changeConfirmation == true)
{
Console.WriteLine("Configuration Change Succeeded");
Console.WriteLine(entity.serviceName + " had its instance count changed to " + entity.amount);
serviceContext.AttachTo("schedule", entity, "*");
serviceContext.DeleteObject(entity);
//Submit the operation to the table service
serviceContext.SaveChangesWithRetries();
Since you are receiving the entity over a query, you do not need to attach the entity.
Thus I think here attachto is not needed at all as you have stated in the comment.
If you need to delete an unattached entity, you can first attach it and mark is as deleted.

AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager

The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.
Is the error message i get. here are the two functions i use...
public IList<string> GenerateVersions(decimal id, decimal fId, string folderName, string filename, string objFile)
{
List<string> generatedFiles = new List<string>();
foreach (var tCmdSets in db.IMG_SETTINGS_CMDSETS.Where("it.SETTINGS_FOLDER_ID = #folderid", new ObjectParameter("folderid", id)))
{
var strDestinationPath = ImageResizer.Util.PathUtils.RemoveExtension(Path.Combine(tmpDefaultFolder, tCmdSets.SETTINGS_CMDSET_DESTINATION, filename));
ResizeSettings objResizeCommand = new ResizeSettings(tCmdSets.SETTINGS_CMDSET_COMMAND);
var strCreatedFile = ImageBuilder.Current.Build(objFile, strDestinationPath, objResizeCommand, false, true);
generatedFiles.Add("### File created: (" + folderName + " » " + tCmdSets.SETTINGS_CMDSET_NAME + " ») " + Path.GetFileName(strCreatedFile));
IMG_UPLOAD_GENERATED_FILES tObjGenerated = new IMG_UPLOAD_GENERATED_FILES();
tObjGenerated.UPLOAD_GENERATED_FILE_NAME = Path.GetFileName(strCreatedFile);
tObjGenerated.UPLOAD_GENERATED_PATH = Path.GetDirectoryName(strCreatedFile);
tObjGenerated.SETTINGS_CMDSET_ID = tCmdSets.SETTINGS_CMDSET_ID;
tObjGenerated.UPLOAD_FILE_ID = fId;
dbHandler.IMG_UPLOAD_GENERATED_FILES.AddObject(tObjGenerated);
dbHandler.SaveChanges();
}
return generatedFiles;
}
public ActionResult UploadBulkFiles(decimal id)
{
IMG_SETTINGS_FOLDERS img_settings_folders = db.IMG_SETTINGS_FOLDERS.Single(i => i.SETTINGS_FOLDER_ID == id);
string strBulkDirectory = Path.Combine(tmpDefaultFolder, img_settings_folders.SETTINGS_FOLDER_BULK);
string[] objFiles = Directory.GetFiles(strBulkDirectory);
List<string> lstOuput = new List<string>();
foreach (var tFile in objFiles)
{
System.IO.File.Move(tFile, Path.Combine(tmpDefaultFolder, "masters", img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile)));
lstOuput.Add("### File moved to masters (" + img_settings_folders.SETTINGS_FOLDER_NAME + " ») " + Path.GetFileName(tFile));
IMG_UPLOAD_FILES tObjUploadedFile = new IMG_UPLOAD_FILES();
tObjUploadedFile.UPLOAD_FILE_NAME = Path.GetFileName(tFile);
tObjUploadedFile.SETTINGS_FOLDER_ID = img_settings_folders.SETTINGS_FOLDER_ID;
dbHandler.IMG_UPLOAD_FILES.AddObject(tObjUploadedFile);
dbHandler.SaveChanges();
var objGeneratedFiles = GenerateVersions(img_settings_folders.SETTINGS_FOLDER_ID,tObjUploadedFile.UPLOAD_FILE_ID, img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile), Path.Combine(tmpDefaultFolder, "masters", img_settings_folders.SETTINGS_FOLDER_NAME, Path.GetFileName(tFile)));
lstOuput.AddRange(objGeneratedFiles);
}
if (lstOuput.Count > 0)
{
return PartialView("UploadSingleFile", lstOuput);
}
else
{
return PartialView("NoUploads");
}
}
DATA MODEL
IMG_UPLOAD_FILE
UPLOAD_FILE_ID (PK)
UPLOAD_FILE_NAME
SETTINGS_FOLDER_ID
IMG_UPLOAD_GENERATED_FILES
UPLOAD_GENERATED_FILE_ID (PK)
UPLOAD_GENERATED_FILE_NAME
UPLOAD_GENERATED_FILE_PATH
SETTINGS_CMDSET_ID
UPLOAD_FILE_ID
I had the exact same scenario with Entity Model based on Oracle database. The implementation of Identity is done by trigger so when adding the tables to the model it does not set the StoreGenertedPattern property of the identity column to Identity since it doens't aware that this column is identity.
There is a need to open model editor, locate the entity in the model, click on the key column and set the StoreGenertedPattern property to 'Identity' manually.
The closest I can come to finding an answer is:
Because Oracle uses a Sequence + Trigger to make "Auto Ident" values, it seems like when the entity framework adds an object at saves it, the value return is still 0, because the trigger/sequence haven't updated it yet.
Because of the 0 number, the ObjectMannager will think that multiple objects with the entity key of 0 are in conflict.
I don't have a "bullet proof" solutions, but have rewritten my solutions to handle it another way.
\T
This might not be related to your problem but I was getting this problem on a web page with an ajax manager running until I did this:
...
private static _objectContext;
protected void Page_Init(object sender, EventArgs e)
{
_objectContext = new ObjectContext();
}
...
protected void _ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
e.Context = _objectContext;
}
protected void _ContextDisposing(object sender, EntityDataSourceContextDisposingEventArgs e)
{
e.Cancel = true;
}
Creating the ObjectContext in Page_Load when not a postback caused that very exception for me.

Why can't I insert record with foreign key in a single server request?

I'm tryring to do a simple insert with foreign key, but it seems that I need to use db.SaveChanges() for every record insert. How can I manage to use only one db.SaveChanges() at the end of this program?
public static void Test()
{
using (var entities = new DBEntities())
{
var sale =
new SalesFeed
{
SaleName = "Stuff...",
};
entities.AddToSalesFeedSet(sale);
var phone =
new CustomerPhone
{
CreationDate = DateTime.UtcNow,
sales_feeds = sale
};
entities.AddToCustomerPhoneSet(phone);
entities.SaveChanges();
}
}
After running the above code I get this exception:
System.Data.UpdateException: An error occurred while updating the entries. See the InnerException for details. The specified value is not an instance of a valid constant type
Parameter name: value.
EDIT: Changed example code and added returned exception.
Apperantly using UNSIGNED BIGINT causes this problem. When I switched to SIGNED BIGINT everything worked as it supposed to.
I tried to do this "the right way":
And then I wrote this little test app to scan a directory, store the directory and all its files in two tables:
static void Main(string[] args)
{
string directoryName = args[0];
if(!Directory.Exists(directoryName))
{
Console.WriteLine("ERROR: Directory '{0}' does not exist!", directoryName);
return;
}
using (testEntities entities = new testEntities())
{
StoredDir dir = new StoredDir{ DirName = directoryName };
entities.AddToStoredDirSet(dir);
foreach (string filename in Directory.GetFiles(directoryName))
{
StoredFile stFile = new StoredFile { FileName = Path.GetFileName(filename), Directory = dir };
entities.AddToStoredFileSet(stFile);
}
try
{
entities.SaveChanges();
}
catch(Exception exc)
{
string message = exc.GetType().FullName + ": " + exc.Message;
}
}
}
As you can see, I only have a single call to .SaveChanges() at the very end - this works like a charm, everything's as expected.
Something about your approach must be screwing up the EF system.....
it might be related with the implementation of AddToSalesFeedSet etc..
there is chance that you are doing commit inside ?
any way, my point is that i encountered very close problem, was tring to add relation to new entity with existed entity that been queried earlier - that has unsigned key
and got the same exception;
the solution was to call Db.collection.Attach(previouslyQueriedEntityInstance);

Categories

Resources