strange nhibernate + linq + mysql exception - mysql

I'm hitting a strange error when running a query in nhibernate using linq.
If I run the query in directly in mysql, everything works. If I rerun the linq query, I get no error, but only the id field (a string) is fetched. If I run the query many times, sometimes the first row is fetched correctly...
The only thing my google-fu found was this mysql bug, but I cannot see how they are related.
EDIT: It seems related to a varbinary(128) field I have in my database. If I remove this mapping, everything works again. I'm mapping this to a byte[] field in my class.
EDIT: I'm using NHibernate 2.1.2.4000 NHibernate.Linq 1.1.0.1001 (the newest GA versions), and I've tried with MySql Connector 6.1.2 and 6.2.4 (6.3.5 failed to install for some reason)
NHibernate.Util.ADOExceptionReporter [(null)] - System.IndexOutOfRangeException: Buffer index must be a valid index in buffer
at MySql.Data.MySqlClient.MySqlDataReader.GetBytes(Int32 i, Int64 fieldOffset, Byte[] buffer, Int32 bufferoffset, Int32 length)
at NHibernate.Driver.NHybridDataReader.GetBytes(Int32 i, Int64 fieldOffset, Byte[] buffer, Int32 bufferoffset, Int32 length)
at NHibernate.Type.AbstractBinaryType.Get(IDataReader rs, Int32 index)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name)
at NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Type.AbstractType.Hydrate(IDataReader rs, String[] names, ISessionImplementor session, Object owner)
at NHibernate.Persister.Entity.AbstractEntityPersister.Hydrate(IDataReader rs, Object id, Object obj, ILoadable rootLoadable, String[][] suffixedPropertyColumns, Boolean allProperties, ISessionImplementor session)
at NHibernate.Loader.Loader.LoadFromResultSet(IDataReader rs, Int32 i, Object obj, String instanceClass, EntityKey key, String rowIdAlias, LockMode lockMode, ILoadable rootPersister, ISessionImplementor session)
at NHibernate.Loader.Loader.InstanceNotYetLoaded(IDataReader dr, Int32 i, ILoadable persister, EntityKey key, LockMode lockMode, String rowIdAlias, EntityKey optionalObjectKey, Object optionalObject, IList hydratedObjects, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRow(IDataReader rs, ILoadable[] persisters, EntityKey[] keys, Object optionalObject, EntityKey optionalObjectKey, LockMode[] lockModes, IList hydratedObjects, ISessionImplementor session)
at NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies)
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters)
Has anyone encountered this error before?

I found the error.
It's a NHibernate/MySql bug where it throws if the binary field is empty.

Related

Mysql EF Core char column with null value throws ArgumentOutOfRangeException

I had a requirement to read some data from a MySql server for an API solution.
The database was scaffolded and we came across a problem where GUIDs are stored in a 'char(36) DEFAULT NULL'
when trying to read entities with that column and the database value is null the following exception is thrown:
Exception thrown: 'System.ArgumentOutOfRangeException' in System.Text.Encoding.CodePages.dll
Exception thrown: 'System.ArgumentOutOfRangeException' in System.Private.CoreLib.dll
Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'DbContext'.
System.ArgumentOutOfRangeException: Non-negative number required. (Parameter 'count')
at System.Text.EncodingNLS.GetString(Byte[] bytes, Int32 index, Int32 count)
at MySql.Data.MySqlClient.NativeDriver.ReadColumnValue(Int32 index, MySqlField field, IMySqlValue valObject)
at MySql.Data.MySqlClient.ResultSet.ReadColumnData(Boolean outputParms)
at MySql.Data.MySqlClient.ResultSet.NextRow(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlDataReader.Read()
at System.Data.Common.DbDataReader.ReadAsync(CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
System.ArgumentOutOfRangeException: Non-negative number required. (Parameter 'count')
at System.Text.EncodingNLS.GetString(Byte[] bytes, Int32 index, Int32 count)
at MySql.Data.MySqlClient.NativeDriver.ReadColumnValue(Int32 index, MySqlField field, IMySqlValue valObject)
at MySql.Data.MySqlClient.ResultSet.ReadColumnData(Boolean outputParms)
at MySql.Data.MySqlClient.ResultSet.NextRow(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlDataReader.Read()
at System.Data.Common.DbDataReader.ReadAsync(CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
Exception thrown: 'System.ArgumentOutOfRangeException' in Microsoft.EntityFrameworkCore.Relational.dll
Scaffolded model:
public class XTable
{
public int Id { get; set; }
public string ProblemColumn { get; set; }
}
modelBuilder.Entity<XTable>(entity =>
{
entity.HasKey(e => e.Id).HasName("PRIMARY");
entity.ToTable("XTable");
entity.Property(e => e.ProblemColumn)
.HasColumnName("problemColumn")
.HasMaxLength(36)
.IsFixedLength();
}
**Context DBSet**
public virtual DbSet<XTable> XTables{ get; set; }
**Example of use case**
var result = dbContext.XTables.SingleOrDefaultAsync(a => a.Id == id);
Environment:
.Net Standard 2.0 consumed by 3.1 asp netcore
Microsoft.EntityFrameworkCore 3.1.9
MySql.Data.EntityFrameworkCore 8.0.22
Did update dependencies to latest stables as shown above.
As mentioned narrowed it to only when the row column value is null, I tried various variations of the model removing "HasMaxLength", "IsFixedLength" that made no difference.
If the row value in the database is blank or has a guid in it reads fine.
Just wondering if anyone aware of MySQL and ef core with char columns issues?
This is the bug of MySql.Data version 8.0.22. I have the same issue and waiting for the next release.
https://bugs.mysql.com/bug.php?id=101252

How to Include a reference to a table in Invantive Excel add-in

I'm making a financial report in Excel using the data from Exact Online using the Invantive Control Excel Add-in. In Exact Online I have a classification for the General Ledgers. In my Excel file, I would like to match these classifications on my reporting schedule. Therefore, I made a table with a mapping of the Exact Online classifications and the reporting classifications.
Using the Invantive Control Excel add-in, I entered the following SQL query:
select periods_year_reportingyear_attr
, reportingperiod_attr
, division_code
, division_hid
, division_name
, periods_year_years_balance_code_attr
, periods_year_years_balance_description
, '=I_EOL_GL_ACTCLN_CODE($C{E,.,.,^+2,.}, $C{E,.,.,^+5,.})' verdichting_code
, '=I_EOL_GL_ACTCLN_DESCRIPTION($C{E,.,.,^+2,.}, $C{E,.,.,^+5,.})' verdichting_naam
, '=i_eol_bal_year_open($C{E,.,.,^+2,.} , $C{E,.,.,^,.}, $C{E,.,.,^+5,.}) + if($C{E,.,.,^+1,.} = 1, 0, i_eol_bal_pder($C{E,.,.,^+2,.},$C{E,.,.,^,.},1,$C{E,.,.,^+1,.}-1,$C{E,.,.,^+5,.}))' startsaldo
, balance
, '=i_eol_bal_year_open($C{E,.,.,^+2,.} , $C{E,.,.,^,.}, $C{E,.,.,^+5,.}) + i_eol_bal_pder($C{E,.,.,^+2,.},$C{E,.,.,^,.},1,$C{E,.,.,^+1,.},$C{E,.,.,^+5,.})' eindsaldo
, periods_year_years_balance_balancetype_attr
, '=INDEX(tab_reporting[Reporting],MATCH(NUMBERVALUE(I_EOL_GL_ACTCLN_CODE($C{E,.,.,^+2,.}, $C{E,.,.,^+5,.})),tab_reporting[GL Class - Code],0))' reporting
from balancelinesperperiod
order
by periods_year_reportingyear_attr
, reportingperiod_attr
, division_hid
, periods_year_years_balance_code_attr
In which tab_reporting is the name of a table with de mapping of the reporting classifications and the Exact Online. This table is on a different tab within Excel. When I review the data I will see these results:
Which, to me looks oke.
One thing that I don't understand is that it looks like there are 4 fields on position 14. The one formula appears to create 4 different data fields in stead of one.
I could send the Excel file upon request.
The problem is that I end up with this error message:
itgensdf031: Kan velden van blok 'Balans (bal)' niet verversen. Can
not refresh fields completely. The field '});TAB_REPORTING[GL CLASS -
CODE];0))'' has a Formule which will get lost when the field is
deleted since it no longer occurs in the SQL.
Migrate all relevant field settings that you need to keep and would
get lost when this field is removed. Hire a consultant if you don't
know how to do this.
Type: Invantive.Data.ValidationException at
Invantive.Data.ValidationException..ctor(String messageCode, String
messageText, String kindRequest, String localStackTrace, String nk,
Exception innerException) at
Invantive.Producer.Control.Utility.RefreshFields(ModelCache
modelCache, iea_blocks_v block, Boolean allowLoadFromCache) at
Invantive.Producer.Control.SyncToDatabaseForm.syncBackGroundWorker_DoWork(Object
sender, DoWorkEventArgs e) at
System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object
argument) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink) at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object
o) at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() at
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() at
Invantive.Producer.Control.Utility.RefreshFields(ModelCache
modelCache, iea_blocks_v block, Boolean allowLoadFromCache) in
File173:line 4362 at
Invantive.Producer.Control.SyncToDatabaseForm.syncBackGroundWorker_DoWork(Object
sender, DoWorkEventArgs e) in File174:line 299 Type:
Invantive.Data.ValidationException at
Invantive.Data.ValidationException..ctor(String messageCode, String
messageText, String kindRequest, String localStackTrace, String nk,
Exception innerException) at
Invantive.Producer.Control.SyncToDatabaseForm.syncBackGroundWorker_DoWork(Object
sender, DoWorkEventArgs e) at
System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object
argument) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink) at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object
o) at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() at
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Invantive Control for Excel (stable-20161021-2025-ge3e5e61 Prod,
L162135034)
It seems that you have managed through a bug somewhere to create multiple fields at position 14. This is a corruption of the repository.
I recommend to first remove the fields at position 14 by:
unchecking their properties
remove the part from the SQL that defines the fields at position 14 (save it somewhere),
and then pressing Refresh in the fields tab.
Check that the fields at position 14 are gone.
The re-add the part from the SQL that defines the fields at position 14.
It should work again.

Log error in SSRS

I have asp.net Web application where in we are calling SSRS Report and showing it in Report Viewer Control on aspx page. I got the following error in log. Can anyone help me finding root cause for the same.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Microsoft.Reporting.WebForms.ReportServerException: The report execution rs3enq55nl1zcu55tprb5zmo has expired or cannot be found. (rsExecutionNotFound) at Microsoft.Reporting.WebForms.ServerReportSoapProxy.OnSoapException(SoapException e) at Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.ProxyMethodInvocation.Execute[TReturn](RSExecutionConnection connection, ProxyMethod1 initialMethod, ProxyMethod1 retryMethod) at Microsoft.Reporting.WebForms.ServerReport.EnsureExecutionSession() at Microsoft.Reporting.WebForms.ServerReport.LoadViewState(Object viewStateObj) at Microsoft.Reporting.WebForms.ServerReport..ctor(SerializationInfo info, StreamingContext context) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.SerializationInvoke(IRuntimeMethodInfo method, Object target, SerializationInfo info, StreamingContext& context) at System.Runtime.Serialization.ObjectManager.CompleteISerializableObject(Object obj, SerializationInfo info, StreamingContext context) at System.Runtime.Serialization.ObjectManager.FixupSpecialObject(ObjectHolder holder) at System.Runtime.Serialization.ObjectManager.DoFixups() at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.
Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, IMethodCallMessage methodCallMessage) at MerrillLynch.Framework.Integration.MLIFSessionDBBase.DeserializeObject(Byte[] data) at MerrillLynch.Framework.Integration.MLIFLegacyStateDB.GetSessionStateItem(String SessionID, String SessionStateID) at MerrillLynch.Framework.Integration.MLIFLegacyStateDB.Get(String SessionID, String SessionStateID, String SessionStateName) at MerrillLynch.Framework.Integration.Session.GetSessionData(CSessionKeyInfo oCSessionKeyInfo) at MerrillLynch.Framework.Integration.MLIFSession.GetSimple(String key)

Passing SqlGeometry To Simple.Data Stored Procedure

I am trying to pass a SqlGeometry type to a stored procedure using Simple.Data and SQL Server 2008. The stored procedure definition looks like this:
CREATE PROCEDURE [dbo].[spUpdateDamLocation]
(
#DamID int,
#Shape geometry
)
The call I am using for Simple.Data looks like this:
var db = Simple.Data.Database.OpenConnection(dbConn);
db.spUpdateDamLocation(DamID: damLocation.DamID, Shape: damLocation.Shape);
Where dbConn is a connection string, damLocation.DamID is an integer and damLocation.Shape is a SqlGeometry object.
The error I am getting is:
System.ArgumentException: UdtTypeName property must be set for UDT parameters.
at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.SetUpRPCParameters(_SqlRPC rpc, Int32 startCount, Boolean inSchema, SqlParameterCollection parameters)
at System.Data.SqlClient.SqlCommand.BuildRPC(Boolean inSchema, SqlParameterCollection parameters, _SqlRPC& rpc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at Simple.Data.Ado.DbCommandExtensions.TryExecuteReader(IDbCommand command)
at Simple.Data.Ado.ProcedureExecutor.ExecuteReader(IDbCommand command)
at Simple.Data.Ado.ProcedureExecutor.Execute(IDictionary`2 suppliedParameters, IDbTransaction transaction)
at Simple.Data.Ado.ProcedureExecutor.Execute(IDictionary`2 suppliedParameters)
at Simple.Data.Ado.AdoAdapter.Execute(String functionName, IDictionary`2 parameters)
at Simple.Data.Database.ExecuteFunction(Object& result, ExecuteFunctionCommand command)
at Simple.Data.DataStrategy.TryInvokeFunction(String functionName, Func`1 getFunctionArguments, Object& result)
at Simple.Data.DataStrategy.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
at CallSite.Target(Closure , CallSite , Object , Int32 , SqlGeometry )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
Is there a way to specify a specific UDT of the parameter in Simple.Data? If I were just using ADO.NET I would do something like this:
SqlParameter sqlParam = sqlCmd.Parameters.Add("#Shape", SqlDbType.UDT);
sqlParam.UdtTypeName = "geometry";
sqlParam.Value = myTypeOfSqlGeometry;
Simple.Data doesn't currently handle user-defined types at the moment. Issue 163 on github raised a similar question several months ago as encountering a UDT crashed the SqlSchemaProvider. The bug was fixed but it doesn't look like there has been any further development into supporting SqlGeometry, SqlGeography and the like.
A stored procedure, as your're trying would seem to be the best way to go, but as UDTs aren't explicitly supported, perhaps sending the SqlGeometry object as its WKT literal equivalent with a call to ToString() would work?
var db = Simple.Data.Database.OpenConnection(dbConn);
db.spUpdateDamLocation(DamID: damLocation.DamID, Shape: damLocation.Shape.ToString());
Also, With Simple.Data v1 just around the corner, I'd suggest opening a new issue for UDT support to be added in v1.1 so you don't need to go through such hoops in the future.

Entity Framework SQL Exception: The supplied value is not a valid instance of data type float

I have an application using the Entity Framework with a SQL Server 2008 (Express) database. I'm getting an intermittent error while doing an update to an entity in the database which indicates that 'the supplied value is not a valid instance of data type float'. However, as best I can tell, the values it's setting will always be floats. They're cast from integers, but even still will always yield floats. If the code did manage to create an invalid float somehow, I would have thought that .NET would complain about it before it even got to SQL Server.
I've included the full exception, code extracts, and schema below.
Is there anything I could be missing here - for example, could a single value be considered a float in .NET but not in SQL Server? Alternatively, is there any way I can programmatically log the precision and scale of a float so that I can diagnose what's going on if the problem comes up again?
I've added some additional logging to try to capture exactly what's going on here, but this is an intermittent problem and I can't reproduce it myself.
The error is:
System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. --->
System.Data.SqlClient.SqlException: The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 4 ("#1"): The supplied value is not a valid instance of data type float. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
--- End of inner exception stack trace ---
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Objects.ObjectContext.SaveChanges()
at MyApplication.ImageProcessing.ProcessImage(Image image) in C:\Code\ImageProcessing.cs:line 224
Here's the code that is being executed. (Note that the Image class is the entity class from Entity Framework.)
private static System.Random _randomLocation = new System.Random();
private void ProcessImage(Image image)
{
float x = _randomLocation.Next(668); // note: the System.Random.Next method always returns an int
float y = 0 - image.Height; // note: image.Height is an int and is always around 300-600 in value in this application
image.X = x;
image.Y = y;
_dataContext.SaveChanges();
}
The schema extract for the table that this is referring to is:
CREATE TABLE Image
(
ImageID uniqueidentifier NOT NULL PRIMARY KEY,
X float NOT NULL,
Y float NOT NULL
)
Also I should note that the EF model uses the data type Single for the X and Y columns.
I got this exact same error. It turns out I was dividing a float by zero. This didn't throw an exception in the code at the time I did the division; when I tried to save this value in the database I got the error.
Hope this is useful to some of you reading the question - Thanks John for raising it.
Well, you already mentioned that you are trying to assign int to float. Try to convert that to float by multiply by 1.0.
float x = _randomLocation.Next(668); // note: the System.Random.Next method always returns an int
float y = 0 - image.Height; // note: image.Height is an int and is always around 300-600 in value in this application