Entity Framework 4 maps DateTimeOffset to SQL datetime in Visual Studio 2010 - entity-framework

I'm using Visual Studio 2010 RTM with .NET/Entity Framework 4 RTM with a model driven design approach.
When I create an entity with a DateTimeOffset field the EF modeler tries to map the DateTimeOffset to a SQL datetime instead of a SQL datetimeoffset.
I'm using SQL Server 2008 Express so the datetimeoffset is supported in the database.
Visual Studio comes up with this error:
Error 2019: Member Mapping specified is not valid. The type 'Edm.DateTimeOffset[Nullable=False,DefaultValue=,Precision=]' of member 'Created' in type 'Data.SqlStorage.MyType' is not compatible with 'SqlServer.datetime[Nullable=False,DefaultValue=,Precision=3]' of member 'Created' in type 'Data.SqlStorage.Store.MyTypes
If I edit the type directly in the EDMX StorageModels xml section I get the following error:
Error 40: The Type datetimeoffset is not qualified with a namespace or alias. Only PrimitiveTypes can be used without qualification.
Why doesn't the modeler just correctly map this to a SQL datetimeoffset type?
This problem also occured when I was still working with the beta versions of Visual Studio 2010 & .NET framework 4.

In the RTM release, you can do something like this in your DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<EntityName>().Property(p => p.PropertyName).HasColumnType("datetimeoffset");
}
This is also useful for telling Entity Framework Code First to use datetime2 instead of datetime when generating your database.

Try going the other way (DB->Model). It worked for Julie Lerman. It seems to me your manually-edited EDMX should also work if you qualify the DateTimeOffset with a namespace.

The solution was to update from DB once, AFTER you change manually in the script sql and generated the db. I did it and after I checked my table mapping and the data type was modified to DATE instead of DATETIME. I think the same can be applied if you want to change to DATETIME2.

Related

Entity Framework Core Data Type Conversion differences between SQLite vs SQLServer

I have a SQLite and SQL Express databases both of which have a table with the columns as below:
my simplified Entity look as below:
public class Customer
{
public string BusinessIdentifier { get; set; }
}
if you notice the datatype is different between the Database bigint vs string on my entity for an example.
I have used a Fluent API to do the mapping as shown below:
entity.Property(p => p.BusinessIdentifier).HasColumnName("CUSTOMER")
on the SQLite when i use options.UseSqlite(connectionString); this work just fine. For SQLite connectionString="Data Source=my_db.db"
however when I use SQL Server Express using options.UseSqlServer(connectionString); it starts to give me errors on the type mismatch.
I have to explicitly handle this conversion on the Fluent API as below:
entity.Property(p => p.BusinessIdentifier).HasColumnName("CUSTOMER").HasConversion(v => Convert.ToInt64(v), v => v.ToString());
SQL Server connectionString="Data Source=my_machine\SQLEXPRESS;Initial Catalog=my_db;Integrated Security=True;"
Question:
Can someone please explain why is this difference between the 2 types of databases and is it really needed to be so specific in every case?
Regards
Kiran
SQLite does not force for data type constraints, It allows you the store a value which is of different data type, so this might be the reason that your code works fine with SQLite, On the other hand, SQL Server enforces you to have to the same datatype.
You can refer to this doc https://www.sqlite.org/datatype3.html.

NPGSQL date time array

I'm attempting to use the timestamp[] field type in Postgres with NPGSQL, so that I can use the DateTime[] type in my Entity Framework models.
I've added this to my EF code first model.
[Column("HostUnavailableDates", TypeName = "timestamp[]")]
public DateTime[] HostUnavailableDates { get; set; }
I've created a migration and the database has updated successfully.
However I am getting this error when executing transactions with the model.
Message: System.InvalidOperationException : The property 'HostApplication.HostUnavailableDates' could not be mapped, because it is of type 'DateTime[]' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
I've followed this answer which does not use any type of ignoring of the property. Is there something I need to do for the DateTime type in addition to what I'm currently doing?
Is DateTime in fact not supported at all in this case?
I'm using EF Core.
I'm assuming you're using Entity Framework 6.x. If that's the case, then arrays simply aren't supported, you'll have to switch to Entity Framework Core.

Is Time Datatype in SQL Server 2008 R2 supports Entityframework with MVC4

I am using ASP.NET MVC4 with Entityframework.
Does Entityframework supports new Time datatype of SQL.
Thank you
Yes it is supported. If you have table which uses Time SQL type it will be recognized as EDM.Time and generated entity will use TimeSpan as property type. In the same way it works with code first approach. If you map property with TimeSpan type the table will contain SQL Time column.

Entity Framework & SQL Compact Edition - how do I get ntext?

The answer to my question should be quite obvious, but I cannot find it. I have a edmx file that has one table. There is a field of type string. EF always generates nvarchar for that (which is kind of expected), but I need an ntext instead of nvarchar for that field as 4000 is too small for me.
So tell me - what is the proper way to tell EF to generate ntext fields?
PS Using Entity Framework 4, SQL CE 3.5
I guess you are using model first, don't you? You can simply create custom T4 template for SQL DDL generation and include logic which will use NTEXT when field is defined with max size.
Default template is on:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen\SSDLToSQL10.tt
Just copy this template and find the logic where data type is created. Once you have your template change DDL Generation Template in model properties (in the designer) to your modified version.
There is much more you can do with generation template because you can add some annotations to your model (XML) and use them for custom logic in the SQL generation process.
Just set the property "MaxLength" in the Designer to "Max". This will generate a ntext field in the SQL CE DB.
If your project contains an ADO.Net Entity Data Model (.edmx) then see Ladislav's excellent answer.
But if you're using the Code First libraries and your project doesn't contain a .edmx then you can use the System.ComponentModel.DataAnnotations.ColumnAttribute to specify the column type:
using System.ComponentModel.DataAnnotations;
public class Note {
[Column("Note", TypeName="ntext")]
public string Note { get; set; }
}

Entity Framework - Mapping decimal(13,0) problem

I'm migrating the aplication of my company (that nowadays run over SQL Server and Oracle) to ASP NET MVC and Entity Framework for persistence.
A create my Entity Model based on SQL Server Database e separately I create a SSDL for Oracle (for Oracle I use DevArt dotConnect for Oracle Provider) and I get some pain troubles.
My table primary keys are on SQL Server are of type decimal(13,0) and on Oracle are number(13,0) but Oracle map it's type to Int64 and SQL Server to decimal, but I need that SQL Server map it to Int64.
I make these modification manually on Entity Data Model and for create records it's works fine, but when I have to delete or update some record I got these error:
The specified value is not an instance of type 'Edm.Decimal'
Parameter name: value
at System.Data.Common.CommandTrees.DbConstantExpression..ctor(DbCommandTree commandTree, Object value, TypeUsage constantType)
at System.Data.Mapping.Update.Internal.UpdateCompiler.GenerateValueExpression(DbCommandTree commandTree, EdmProperty property, PropagatorResult value)
at System.Data.Mapping.Update.Internal.UpdateCompiler.GenerateEqualityExpression(DbModificationCommandTree commandTree, EdmProperty property, PropagatorResult value)
at System.Data.Mapping.Update.Internal.UpdateCompiler.BuildPredicate(DbModificationCommandTree commandTree, PropagatorResult referenceRow, PropagatorResult current, TableChangeProcessor processor, Boolean& rowMustBeTouched)
at System.Data.Mapping.Update.Internal.UpdateCompiler.BuildDeleteCommand(PropagatorResult oldRow, TableChangeProcessor processor)
at System.Data.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode changeNode, UpdateCompiler compiler)
Someone can help me?
Why Entity Framework mapping are so fixed? It could be more flexible?
Ps.: The error that I got, I suspect that is because of a association.
I have a Entity named Province and another named Country and I think that the association between these Entities are causing the problem at update and delete.
Regards,
Douglas Aguiar
This may or may not help you, but i had the same error from doing this same thing. So I edited the Conceptual model and change the primary key field from Int32 to Decimal. So far, seems to have fixed things. I still need to test again against Sql Server and make sure this didnt break it.
I was getting the error "The specified value is not an instance of type 'Edm.Decimal' Parameter name: value" as you posted in your question. I had changed the default data types from Decimal to Int32 as this better reflects the true typing. When I first hit this error I rolled back the type changes and was still getting an exception but it changed just slightly but led to further digging. Bottom line, in my scenario we were expecting a trigger to populate the PK during persistence via Before Insert directive. The problem was that the domain class built by EF was setting the PK at 0 so the trigger was never firing as the incoming PK was not null. Of course EF will not let you set the Entity PK to be nullable. Maybe this will help someone else in the future.