Entity "GenericArguments[2] System.SIngle" Error - c#

Can anyone help me to understand what this error message (below) is trying to tell me?
I have code that successfully writes records to my SQL Server database table, and code that reads it back. But I've been struggling to create code to DELETE records from this same table.
An example of what I am trying to do:
public void DeleteUnfinishedTransaction(int uftID)
{
var uft = _dataContext.UnfinishedTransaction.Where(t => t.ID == uftID).FirstOrDefault();
if (uft != null)
{
_dataContext.UnfinishedTransaction.DeleteOnSubmit(uft);
}
_dataContext.SubmitChanges();
}
I've reworded this several different ways but when the "SubmitChanges" line is reached, this error is always thrown:
GenericArguments[2], 'System.Single', on
'System.Data.Linq.Mapping.PropertyAccessor+Accessor`3[T,V,V2]'
violates the constraint of type 'V2'.
I've been searching for information on this error to try to understand it and have been coming up empty-handed.
A little more info: this is a web application for which the 'metadata' (e.g., EDML, etc.) has been lost or destroyed, so all of the data access code which is normally auto-generated has to be written "by hand." I may have made a mistake somewhere else in the code -- the code above is just what triggers the actual error.
Any help understanding this would be greatly appreciated.

I struggled with this for days before posting a question here, but less than two hours after I did, I backed into the root of the problem.
In the code defining the structure of the fields in the 'UnfinishedTransaction' object (above), there were some unfortunate conversions being attempted between C#'s "single" and "double" data types, and SQL Server's "float." Once I fixed that I stopped getting the error and all appears well.
I'm surprised that those conversions were not problematic on 'Save' and 'Select,' only on 'Delete.'

Related

Get structure back from Cache fails with cast error when types looks the same

I have the following structure:
struct someData
{
public bool check;
public string text;
}
...
someData sd = new someData(){ check = true, text = "just testing" };
Cache.Insert(cacheInd, sd, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(90));
Then later on the code, I want to retrieve the data from cache, but I get an InvalidCastException:
if (Cache[cacheInd] != null)
{
someData sd = (someData)Cache[cacheInd];//Error here
If I try this:
someData sd = Cache[cacheInd] as someData;
I get:
The as operator must be used with a reference type or nullable type ('ASP._dev_pull_aspx.someData' is a non-nullable value type)
Any ideas on how to solve it?
Here's what I'm doing:
Load page (not cached yet) -> everything is fine
Reload it (cached) -> everything is fine
Change code, not related to it somewhere else in the page -> get the exception
Recycling the cache fixes it (until i change code again)
Note: thanks for MethodMan and Michael Humelsine for explanation of as failure - Why can't I use the as keyword for a struct?, but failure to perform cast is still unclear especially since it works most of the time.
It looks like you get 2 different types with type named the same as result of re-compilation of the page and hence you can't cast one to another despite very similar names/structure.
Why:
in .Net type identity includes full name and assembly identity (name) like "System.Int32 from System.dll v4.0.0.0".
changing an ASPX/CSHTML page produces new assembly with random name but does not trigger recycle of app-domain (especially in debug configuration) till some relatively high threshold of "number of dynamically compiled assemblies" is hit (don't have good link handy, search. I.e. this one talks about diff between ASPX vs. Razor )
You should be able to see complete types if you compare whole Type objects (typeof(someData) vs. Cache[cacheInd].GetType() - one of the properties would be different, i.e. Type.FullName likely candidate.
I'd expect the types to look similar to following (with difference in the name of its assembly):
{ASP._dev_pull_aspx.someData from "ASP._dev_pull_aspx._3333.dll"
{ASP._dev_pull_aspx.someData from "ASP._dev_pull_aspx._7777.dll"
To fix you should move types you care about to compiled assemblies from pages or live with the fact that sometimes types will not match and restart app-domain. Normally rebuilding project or web.config change would trigger app-domain recycle as it is part of recycle triggers along with number of recompilations of individual pages.
Notes:
changing struct someData to class someData would still reproduce the error, but you may see more detailed message instead with as types still will be different
the other common cases of such error are having copy of the same type in several assemblies/namespaces due to code sharing (as in include the same source file into multiple project) and using multiple versions of the same strongly named assembly.
Well, I just tested a struct like yours, stored it in cache and retrieved it with the cast syntax (i.e. (someData)Cache[cacheInd]).
It worked fine with no casting issues and no exceptions. What is the value of the "cacheInd" variable in your example? Can it change between the time it is used to store the item in the cache and the time it retrieves it?
Have you debugged to see what the data type is of the object/struct that IS stored in the cache?
The lack of issues I faced seem to point to something other than an issue with serializing/deserializing a struct.

infinitive loop at the end of action method

Recently I have faced with a very strange problem. My Action method must return JsonResult,and all is good untill the last break point before return (At this moment I have correct json result).Then in browser console I see error 500 (Internal server error).Nothing exception in debugger.When I start to chek every step in debugger with F10,F11 I have noticed something strange.Unexpected infinitive invokes to my model properties (sometimes to model properties,sometimes infinitive invoking functions and then model proerties).I decide that this infinitive loop provoked error (but I still misunderstanding why I couldn't see it in debugger - perhaps this is aspect of IIS debugging).Code hasnt got weak places (I dont show it because it will take much more than few space).I know that my question is not constructive in stackoverflow terminalogy but I hope that somebody has encountered the same problem.I need only ideas.Thanks.
SOLUTION
As noticed #mreyeros and # LastCoder self referencing can be the reason of such behavior.I have cheked my model in details and found this place:
private IEnumerable<CollegeEstimateModel> _initialModels;
public IEnumerable<CollegeEstimateModel> InitialModels
{
get { return _initialModels = _initialModels ?? CreateInitialModelsList(); }
}
where CollegeEstimateModel contains above properties
I have added [ScriptIgnore] attribute and all become ok.
You should start by checking to see if the model that you are trying to serialize to your JSON result does not contain a property with a self referencing property. For example you have an Order object that contains a collection of details. The detail record has a navigation property back up to the parent order, thus causing a loop during serialization of the order object. This is just a guess of course, but hope that it helps

EF5 and Stored Procedure - FunctionImport Not found in Container

I have been dealing with this for a couple weeks now, and figured it was time to bring someone else in. I have been to many sites trying to solve this, but I'll start from the beginning.
This is my first project in mvc and ef, so I have relied on a lot of tutorials.
I started with this one...
http://msdn.microsoft.com/en-us/data/gg699321.aspx
Everything else I find on the web pretty much just shows me the same things, so I figured this was pretty simple.
The stored procedure in question is pretty simple, it just returns a string from a table.
SELECT TOP 1 ConnectionString
FROM tConfig
WHERE Active = 1
I generated an edmx file, like in the article above, and it generated the following code in a context file. I have tried this both with, and without the EntityContainerName next to the procedure.
public virtual ObjectResult<string> psMasterDataSource()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<string>("CentralApp.psMasterDataSource");
}
Where I am using it is also pretty simple.
public string GetMasterDSConn() {
var context = new CentralApp();
var conn = context.psMasterDataSource().SingleOrDefault();
return conn;
}
But when I run it, I get the following error.
The FunctionImport 'psMasterDataSource' could not be found in the container 'CentralApp'.
I saw someone on another site talked about editing the XML, but I couldn't find anything helpful on what to edit. So I am hoping I am missing something simple there.
I appreciate any help on this. I am ready to get this app tested, but this is holding me back.

MVC2 - Records in database not updating - No errors

I'm having an odd little problem with MVC2. I am perorming some CRUD tasks, and I can Create records in the database just fine. But when I go to update a record with the following code nothing seems to happen to the database:
EntityModelConnection entityModelConnection = new EntityModelConnection ();
try {
OrderLogic orderLogic= new OrderLogic ();
EntityObject_Orders orderToUpdate = OrderLogic.GetOrderByID(1);
orderToUpdate.Name = "Laptop";
EntityModelConnection.SaveChanges(); }
My code isn't using names like these, they are just renamed for clarity :)
When I run over this code, no errors are thrown and the correct single record is returned from OrderLogic.GetOrdersByID, but nothing seems to update in the database.
It's a bit hard to find guides on this since most people are using UpdateModel in the controller and I'm doing my logic far from that location, so I can't (seem) to use that feature.
Any thoughts on what I might be missing? Is there something strange about MVC when it comes to updating records I might be missing?
I'm going for a coffee to refresh my brain :)
MVC or no MVC should have no effect on your data layer. I suspect that your order isn't being updated because it either isn't marked as being changed in the persistance layer or you're not getting it from the same persistance layer object that you're saving changes in. How is it that the connection you're creating and saving from is provided to the OrderLogic object to retrieve the EntityObject_Orders object?
It looks like your Order instance came from a different entity connection.

EF 1.0 during creation

I've a strange problem using EF1.0... my problem happenin' only during a creation and I didn't find anything on many forum's thread.
> System.InvalidOperationException: The source query for this EntityCollection or EntityReference cannot be returned when the related object is in either an added state or a detached state and was not originally retrieved using the NoTracking merge option.
at System.Data.Objects.DataClasses.RelatedEnd.CreateSourceQuery[TEntity](MergeOption mergeOption)
at System.Data.Objects.DataClasses.EntityCollection`1.CreateSourceQuery()
at Microsoft.Data.EFLazyLoading.LazyEntityCollection`1.CreateSourceQuery()
at Microsoft.Data.EFLazyLoading.LazyEntityCollection`1.LoadStubs()
at mptradModel.ContextObjects.ChansonWrapper.AttachEntities(Chanson chanson, ChansonRequest request) in (SolutionDir)\ProjectWrapper\ContextObjects\ChansonWrapper.cs:line 115
What is the real problem? I happens when I tried to add an Entity to another entity's list during a command creation.
I.E.: aCommand.Songs.Add(new Song() { Name = "SongName" });
Thank to you guys and sorry for my english ; Im from Quebec and usualy talk french!
UPDATE #1
My line #115 in chansonwrapper (which mean "songwrapper") :
aCommand.Songs.Add(new Song() { Name = "SongName" });
UPDATE #2
Sorry, I were trying to simplify the code to write but I think its just more confusing so here is my real code :
SongWrapper songWrapper = new SongWrapper(this.m_Context);
Song song = songWrapper.Load(request.SongId);
aCommand.Songs.Add(song);
The this.m_Context for my songWrapper ensure that my song returned in in the same context of my "aCommand" or other entity that i could load later/before. This part were alrealy tested so we know it works. One things have changed, is that we moved to "LazyLoading" what we were not using before. More weird, the update works fine! Help meee :oP!
This is certainly not EF 1.0. It must be 4.0 beta. I think it may be a bug in lazy loading. You're doing (from a back revision of your question) if( aCommand.songs.Count() > 0. For an entity in the added state, this should not try to lazily load the songs. But it seems to be trying to do just that. My only suggestion is to work around the bug via something like:
if ((aCommand.EntityState != EntityState.Added)
&& (aCommand.songs.Count() > 0))
...which is a bit kludgy, or turn lazy loading off for this. If you can boil this down to a reproducible test case, you might report it to Microsoft Connect.
By the way, you should generally prefer:
if (aCommand.songs.Any())
... to Count() > 0 as it's more efficient and readable. But that's irrelevant here.

Categories

Resources