Entity Framework exception suddenly - c#

I have this code in my backend:
using (var context = new Db_EnforcementEntities())
{
try
{
DbContextHelper.SetContextConfig(context, false);
VW_ENF_TviotOnePercentage[] test = context.VW_ENF_TviotOnePercentage.ToArray();
}
}
where VW_ENF_TviotOnePercentage is a view which already exists in my EDMX file.
The above code worked perfectly up until several days ago, and I could fetch records which are identical to the records I could see in the database.
For some reason, when I get to the code now, I get an exception:
Object reference not set to an instance of an object
The stack trace points to:
at System.Object.GetType()
at System.Data.EntityKey.ValidateTypeOfKeyValue
What could go wrong in the database to cause this error?

Related

Error when calling a Entitie made by entity framework from edmx model

I'm trying to access my dbEntities that was created through the ADO.Net Entity Data Model, but when I try to access it, it "finds" the database tables but it gives a certain error that I will put immediately below, I already tried everything , change the Metadata, create an application of 0 and tested and it did not work, can anyone help me?
This is a new web application that I'm trying to develop, the front part is all ready, the only problem is this connection to the database, where I've tried a lot, like creating another project, and some tutorials, but even so it does not work, the database I'm trying to access is not local, it's from a server, and I was wondering if I would have a MySQL configuration that might be blocking the SELECT or something
try
{
dbEntitiescontext = new dbEntities();
var listDTO = new List<CompanyDTO>();
var list = context.company.ToList();
foreach (var item in list)
{
listDTO.Add(new CompanyDTO().ToDTO(item));
}
return listDTO ;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
Currently it returns me the following error:
'dbEntities.company.Local' threw an exception of type 'System.Data.Entity.Core.MetadataException'

Missing datagrid boundcolumn in production

Using visual studio and C#, I recently added a new bound column to a data grid and modified the stored procedure to pull the extra field. When I debug it - it shows up fine and displays the data as I expect. When I publish the website and copy the files to the web server, the column is no longer there. It's a pretty straight forward setup. I know the file is being copied etc. What am I missing?
In addition to the comments added above, make sure your added field exists on Production Database.
If it throws an exception that your code swallows up, you would never know.
Example:
private bool SomeMethod(string cmdText) {
bool result = false;
try {
result = Query(cmdText);
} Catch (Exception) {
// Error occurred
}
}
If you had the code above and had an error, you would never know.

VS 2013 bombs out when MVC steps in EF6 call using SQL2014

I have an MVC5 project that is divided into a main XXXX.Site and a XXXX.Data dll that has EF6 connecting to the MS-SQL 2014 database.
When I'm on the MVC controller and press F10 at the call that runs inside the XXXX.Data dll, all goes well. If I go inside the DLL code and put a breakpoint on the actual EF call ...Visual Studio simply bombs out.
I tried different things like re-adding EF6.1.1.1, I on both DLL and MVC site but nothing works. I tried removing and then adding completely EF. I tried a new project and just put the code to run a simple stored proc, I even tried to combine the Data.dll into the MVC Site code moving all DB access to the MVC Site (mainly deleted the DLL itself) ...but nothing worked !!
This is what I noticed so far:
1) if I put a breakpoint on the code I wrote to call this stored procedure ...Visual Studio simply bombs out.
try
{
using (MyDB db = new MyDB())
{
// IF BREAKPOINT IS ON LINE BELOW, EXECUTION STOPS ABRUPTLY
db.MyStoredProc(value1, value2);
}
}
catch (Exception ex)
{
string s = ex.Message;
return false;
}
No exception is raised, and when it occurs the browsers kind of flashes a couple of times. Then this message appears on the Output window:
A first chance exception of type 'System.AccessViolationException' occurred in XXXX.Data.dll
2) If instead I put the breakpoint inside the actual auto generated EF6 code, the program does runs normally.
public virtual int MyStoredProc(string value1, string value2)
{
var value1Parameter = value1 != null ?
new ObjectParameter("Value1", value1) :
new ObjectParameter("Value1", typeof(string));
var value2Parameter = value2 != null ?
new ObjectParameter("Value2", value2) :
new ObjectParameter("Value2", typeof(string));
// IF BREAKPOINT IS ON LINE BELOW, EXECUTION RUNS NORMALLY
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("MyStoredProc", value1Parameter, value2Parameter);
}
Note that I have both EntityFramework and EntitySQLServer dlls on both bin folders (MVC and DLL).
Questions:
Is it an issue with SQL2014? I don't have this happening when connecting to SQL2012.
Is there a setting that will display the actual exception occurred?
Why is VS bombing out instead of displaying the actual error?
I was getting this "Attempted to read or write protected memory exception" error while using a SQL Server stored procedure that had an output parameter of type 'Date'. I tried various things without success and, in the interest of time, settled on the following solution.
1) Remove the output parameter of type date from the stored procedure.
2) Return a string via a select statement in the stored procedure instead.
SELECT CONVERT(char(10), #AsOfDate, 20) AS AsOfDate
3) Convert the string returned from the stored procedure to a DateTime value in C#.
DateTime asOfDate = DateTime.Now;
using (var context = new DA.MyEntities())
{
var procResult = context.myStoredProcedure(myParameter).FirstOrDefault();
DateTime.TryParse(procResult, out asOfDate);
}
I'm not super happy with this compromise, but it did allow me to move forward.

Entity Framework, SQLite and Lazy loading

Hi I had developed a C# Budget application using SQL Compact and EF4, I created the EF model through the VS2010 Entity Data Model template. It is all working very well. However I am considering developing a iPhone app to support cash transactions and thought it would be better to have the back end DB supported on both platforms. After creating the SQLite DB and creating a new model I have come across a problem when trying to access referenced data via the Navigation properties in my model. I am getting a NullReferenceException when trying to display a property of a referenced table.
When using the following code I get the exception on the last line:
BudgetEntities budget = new BudgetEntities();
var accounts = budget.BankAccounts.ToList();
foreach (BankAccount a in accounts)
{
Console.WriteLine("Name:" + a.Description);
Console.WriteLine("Number:" + a.AccountNumber);
Console.WriteLine("Type:" + a.BankAccountType.AccountType); //Exception occurs here.
}
Strange thing is that the exception doesn't occur in this example. I'm not sure what is going on?
BudgetEntities budget = new BudgetEntities();
var accoutTypes = budget.BankAccountTypes;
var account = new BankAccount();
account.ID = Guid.NewGuid();
account.AccountTypeID = accoutTypes.First(t => t.AccountType.StartsWith("Credit")).ID;
account.BSB = "3434";
account.AccountNumber = "32323";
account.Description = "Test";
account.TrackingAccount = true;
budget.AddObject("BankAccounts", account);
budget.SaveChanges();
var accounts = budget.BankAccounts.ToList();
foreach (BankAccount a in accounts)
{
Console.WriteLine("Name:" + a.Description);
Console.WriteLine("Number:" + a.AccountNumber);
Console.WriteLine("Type:" + a.BankAccountType.AccountType); //Exception doesn't happen.
}
This is only a simple example and I know I could fix it by adding .Include("BankAccountTypes") to the query however I have other queries that are quite complex that are creating object which include properties from referenced object with in the query and I am not quite sure how to get around this issue for them.
EDIT:
After having a break between projects I have come back to this problem and I have finally resolved my problem. it had nothing to do with the code. It was with the data. I had converted a SQL Compact database to SQLite via a dump and load and had the syntax wrong for my Guid column data. I was inserting the Guid as '7cee3e1c-7a2b-462d-8c3d-82dd6ae62fb4' when it should have been x'7cee3e1c7a2b462d8c3d82dd6ae62fb4'
Hopefully the hair I pulled out working through this problem will grow back :)
Thanks everyone for your input.
In second example your code snippet begins with:
var accoutTypes = budget.BankAccountTypes;
This loads all bank account types to your application and you don't need lazy loading anymore (EF will automatically recognize that these entities were already loaded and fix relations with bank accounts).
First check if your account class is dynamic proxy (just check type of a in the debugger). If it is not you made some mistake in the class definition and lazy loading will not work. Next check if lazy loading is enabled on your context instance (budget.ContextOptions.LazyLoadingEnabled property).
Make sure the BankAccountType property is declared virtual in BudgetEntities.

Linq to SQL Row Not Found or Changed Exception on Insert Operation Ajax Postback in MVC3

I have an MVC3 View that's posting back a set of input values via Ajax to my controller. My controller is then creating a new FieldTripRoute object on my context and attempting to insert it into the database.
I just can't figure out what's going on. I've triple checked my Designer schema and my DB schema and they match perfectly. So it can't be the normal issue of a column not existing or being nullable in one area but not another. However, I keep receiving a "Row Not Found or Changed" exception every time I attempt to submit changes.
The stack trace on the exception looks like this:
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()
at ManageMAT.Controllers.FieldTripController.RouteAdd(Int32 id, FormCollection collection)
This is the code that's being called to add the new Route object from the Controller:
[HttpPost]
public ActionResult RouteAdd(int id, FormCollection collection)
{
FieldTrip trip = context.FieldTrips.Single(ft => ft.ID == id);
if (trip == null) return Json(new { success = false, message = "Field trip not found." }); ;
try
{
FieldTripRoute tripRoute = new FieldTripRoute();
tripRoute.FieldTripID = trip.ID;
tripRoute.Date = DateTime.Parse(collection["Date"]);
tripRoute.ArrivalTime = DateTime.Parse(collection["ArrivalTime"] + " " + DateTime.Now.ToShortDateString());
tripRoute.DepartureTime = DateTime.Parse(collection["DepartureTime"] + " " + DateTime.Now.ToShortDateString());
tripRoute.Destination = collection["Destination"];
tripRoute.PickupLocation = collection["PickupLocation"];
tripRoute.RouteID = Convert.ToInt32(collection["RouteID"]);
context.FieldTripRoutes.InsertOnSubmit(tripRoute);
context.SubmitChanges();
return Json(new { success = true, message = "Success!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
And here is my Designer and DB Table Columns:
I've also attempted to view the SQL this is outputting in both the logging available on the context object and in SQL Profiler, but it seems to be failing before it's even hitting the Database server.
Edit: Forgot to add one other thing, when I'm initially creating the new FieldTripRoute object at the beginning of the Add action I noticed that it's not retrieving the correct ID from the database identity series. Perhaps this is related?
I've also tried setting the Update Check on every field in the designer to Never just to see if it was some kind of bizarre concurrency collision going on, but I am still receiving the same error.
I'm really at a loss for what could be causing this issue. Any ideas are appreciated.
This message is thrown every time the row is not inserted for whatever reason. For DML statements Linq to SQL checks the number of modified rows. SQL Server returns this count. It is checked to be one.
The big question is why is the count zero and yet no error message is being sent by SQL Server. Start SQL Server profiler and post the SQL that L2S generates. Run the SQL manually and see what happens. Does a row get inserted? Does its identity value get returned?
Edit: More debugging ahead: Shut down SQL server just before you to the SubmitChanges to make sure that the database is not being hit. Lets make sure to cut this branch off the search tree.
Next, step into the Linq to SQL source code to see whats up. If you have R# this is easy: Press ctrl-shift-t, search ChangeProcessor, click and navigate to the "sources from symbol files". Find the function SubmitChanges and put a breakpoint in there. If you don't have R#, you need to dig out some tutorial on the web for this (it's going to take about 5min).
Step through the source to find why the exception is thrown.

Categories