Quantcast
Channel: Entity Framework
Viewing all 10318 articles
Browse latest View live

Commented Unassigned: EF 6.1.2: Migration CreateIndex()/DropIndex() are not bijective [2645]

$
0
0
The automatically computed index name used by __DbMigration.CreateIndex()__ is not of any use when there is a requirement for performing an inverse __DbMigration.DropIndex()__ operation.

So an index added in the Up() method of a manual migration can not be reversed.

Here's the code for reproducing this issue:

```
public partial class IndexTry : DbMigration
{
public override void Up()
{
AddColumn("dbo.T1", "Name", c => c.String(nullable: false, maxLength: 100));
CreateIndex("dbo.T1", "Name", true);
}

public override void Down()
{
DropIndex("dbo.T1", "Name"); // *** fails ***
DropColumn("dbo.T1", "Name"); // *** fails, because DropIndex() failed ***
}
}
```

I suggest either of the following two options to solve this problem:

(a) The Name argument of the CreateIndex() function should __not__ be optional

-or-

(b) the DropIndex() function should accept the same Column parameters as the CreateIndex() function.

For (b): The resulting DropIndex() SQL statement can easily find the index by querying the index columns and excluding all other columns:

```
DECLARE @tableName SYSNAME;
DECLARE @indexName SYSNAME;
DECLARE @columns AS TABLE (Name SYSNAME NOT NULL UNIQUE);

-- set table name here --
SET @tableName = 'dbo. ...'

-- add columns to @columns table here --
INSERT @columns VALUES (' ... ')
INSERT @columns VALUES (' ... ')
INSERT @columns VALUES (' ... ')

DECLARE crsr CURSOR FORWARD_ONLY READ_ONLY
FOR SELECT
i.name
FROM sys.index_columns as ic
INNER JOIN sys.indexes AS i ON ic.index_id = i.index_id
INNER JOIN sys.columns AS sc ON ic.column_id = sc.column_id AND ic.object_id = sc.object_id
LEFT JOIN @columns AS c ON sc.name = c.Name
WHERE ic.object_id = OBJECT_ID(@tableName)
GROUP BY i.name
HAVING SUM(CASE WHEN c.name IS NULL THEN 0 ELSE 1 END) = (SELECT COUNT(name) FROM @columns)
AND SUM(CASE WHEN c.name IS NULL THEN 1 ELSE 0 END) = 0;

OPEN crsr;

FETCH NEXT FROM crsr INTO @indexName

CLOSE crsr;
DEALLOCATE crsr;

IF (@indexName IS NOT NULL) EXEC ('DROP INDEX ' + @indexName)

```
Comments: Ah, I see. I didn't look out for that overload when the error occured. My fault. Sorry.

Created Unassigned: Stop endorsing Stack Overflow [2648]

$
0
0
Stop suggesting to ask questions regarding Entity Framework on Stack Overflow.

There's no one there answering questions. You only get users' stupid answers - if any at all.

If you provide Entity Framework, then support it, too. It is impertinent to push the burdon that's arising from your framework on others' shoulders. No-one there wants it. And no-one there has the skills to answer.

One would expect that if Microsoft spares budget by having Open Source amend their Entity Framework, then at least it should have the balls to provide qualified support.

Created Unassigned: byte converts to SQL as int instead of tinyint [2649]

$
0
0
This is my problem - I want to use a tinyint column in SQL as it has much better performance than int
The enums I want to use in this case are known and small (don't need more than 255 options)
Suggested solution: Why don't we convert byte to tinyint unless the enum is larger than 255 items...

Commented Feature: Support Global Query Filters (Query Interceptors) [945]

$
0
0
Hi,

it's about time i'm looking for a way to implement a row level filtering based on some parameters (in my case, the identity of the user currently logged into my MVC4 application).

I've searched a lot on the net, but no way.

I'm currently using the unit of work + repository pattern, and of course i'm able to easily filter each repository, based on some predefined filter (for example, the current user).

By the way, when navigating navigation properties, there is no an easy way to filter the related entities.

What am i looking for ?

Basically, it would be nice to perform one of the two ways:

- a global filtering: something similar to the NHibernate Global Filtering implementation. Some example:

http://ayende.com/blog/3993/nhibernate-filters
http://www.eiben.weite-welt.com/2010/01/nhibernate_filter/

This could allow ti implement some row-level filtering based on dynamic parameters. All the entities will be filtered, both the one accessed via repository and those accessed via navigation properties.

- an include filtering: something like this:

http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015345-allow-filtering-for-include-extension-method

This could allow navigation properties filtering too, even if i prefer the first method.

What do u think about it?

Could it be implemented easily?

Should i work with query interceptors?

Thank you in advance.

Regards,

aNt1X

Comments: My project has been updated to support linq filter expressions. See if it covers your needs now: https://github.com/jcachat/EntityFramework.DynamicFilters. If there is still something missing, make an issue there and I'll see if I can add support for it.

New Comment on "Code First Annotations"

$
0
0
"For example, database indexes are not represented in the model and so Migrations could detect differences." - "To use add an annotation for a table: " Please, can someone put this article into good English. I'm not a linguist, but merely a software architect.

New Comment on "Code First Annotations"

$
0
0
"For example, database indexes are not represented in the model and so Migrations could detect differences." - "To use add an annotation for a table: " Please, can someone put this article into good English. I'm not a linguist, but merely a software architect. Julia Lerman, where are you when you're needed?

Created Unassigned: Error using "Update-database" from EF migration in Azure Mobile Service [2650]

$
0
0
Hey guys,


I am playing again with a issue related with migrations and I did not understand one thing.

1 - Create a new Azure Mobile Service Project
3 - Defined the connection for a database
4 - Ran the "add-migration Initial"
5 - Ran "update-database" and it fails with this error

```
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201501172006390_Initial].
Applying explicit migration: 201501172006390_Initial.
System.Data.SqlClient.SqlException (0x80131904): Cannot create more than one clustered index on table 'migrations.TodoItems'. Drop the existing clustered index 'PK_migrations.TodoItems' before creating another.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:0942ae41-6373-4032-8d35-9a096dccca75
Error Number:1902,State:3,Class:16
Cannot create more than one clustered index on table 'migrations.TodoItems'. Drop the existing clustered index 'PK_migrations.TodoItems' before creating another.

```

but if I use

```
var migrator = new DbMigrator(new Configuration());
migrator.Update();
```

and do a deploy it works well.




When I do "update-database -script" the result is

```
IF schema_id('migrations') IS NULL
EXECUTE('CREATE SCHEMA [migrations]')
CREATE TABLE [migrations].[TodoItems] (
[Id] [nvarchar](128) NOT NULL,
[Text] [nvarchar](max),
[Complete] [bit] NOT NULL,
[Version] rowversion NOT NULL,
[CreatedAt] [datetimeoffset](7) NOT NULL,
[UpdatedAt] [datetimeoffset](7),
[Deleted] [bit] NOT NULL,
CONSTRAINT [PK_migrations.TodoItems] PRIMARY KEY ([Id])
)
CREATE CLUSTERED INDEX [IX_CreatedAt] ON [migrations].[TodoItems]([CreatedAt])
CREATE TABLE [migrations].[__MigrationHistory] (
[MigrationId] [nvarchar](150) NOT NULL,
[ContextKey] [nvarchar](300) NOT NULL,
[Model] [varbinary](max) NOT NULL,
[ProductVersion] [nvarchar](32) NOT NULL,
CONSTRAINT [PK_migrations.__MigrationHistory] PRIMARY KEY ([MigrationId], [ContextKey])
)
INSERT [migrations].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201501172006390_Initial', N'AzureMobileService.Migrations.Configuration', 0x1F8B0800000000000400CD58CD6EE33610BE17E83B103AB540D64CB2876E0379175E27298CAEE360E5EC9D96C60E5B8A5449CAB55BF4C97AE823FD7DC5E8D368AD0132EBB35E042BC3571C35BB2350BF19F2E80899ABF0D08BF94A67E1E0C439CF093766D03307CDEEE5E0D3E6470CFF160C5FD510EE9386C41765A45183967B2672A9CAF260904D46E59656F5A66019F6091B69CB972CB4F8380463B2D7C82F4CA4B8E52E5E403491B3D4627F8C8C81782176DE607C7ADC7F364DEF72F6674996C8D708016972D7EA33F931E522AA78DFEF69A60310AE6D8A1381ACF0351AE156DB0AE941C99E4045FA6E2101E98EFF1C508511CCCC64C0D6700E377C2DFA042B166ECB3BFE30C8CB85D84DBB7FCB19B6746C0A8CDADE7D98A3EECBDCFB7F0018377D2CCB130000 , N'6.1.1-30610')

```

and if I got the SQL script from the todoitem table the sql script is

```
USE [migrations_db]
GO

/****** Object: Table [migrations].[TodoItems] Script Date: 1/17/2015 8:16:07 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [migrations].[TodoItems] (
[Id] NVARCHAR (128) NOT NULL,
[Text] NVARCHAR (MAX) NULL,
[Complete] BIT NOT NULL,
[Version] ROWVERSION NOT NULL,
[CreatedAt] DATETIMEOFFSET (7) NOT NULL,
[UpdatedAt] DATETIMEOFFSET (7) NULL,
[Deleted] BIT NOT NULL
);


GO
CREATE CLUSTERED INDEX [IX_CreatedAt]
ON [migrations].[TodoItems]([CreatedAt] ASC);


GO
ALTER TABLE [migrations].[TodoItems]
ADD CONSTRAINT [PK_migrations.TodoItems] PRIMARY KEY NONCLUSTERED ([Id] ASC);


Where is the definition made by AMS Team to the EntityData (todoitem is a EntityData )

```
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Index(IsClustered = true)]
[TableColumn(TableColumnType.CreatedAt)]
public DateTimeOffset? CreatedAt { get; set; }
[TableColumn(TableColumnType.Deleted)]
public bool Deleted { get; set; }
[Key]
[TableColumn(TableColumnType.Id)]
public string Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[TableColumn(TableColumnType.UpdatedAt)]
public DateTimeOffset? UpdatedAt { get; set; }
[TableColumn(TableColumnType.Version)]
[Timestamp]
public byte[] Version { get; set; }

```
```

Updated Wiki: Code First Annotations

$
0
0

Code First Annotations

Migrations can detect any differences when a Code First model is changed and use this information to generate SQL to keep the database up-to-date. However, Code First makes use of the Entity Data Model (EDM) to do this and so can only track differences that are represented in the model. For example, database indexes are not represented in the model and so Migrations could not detect differences.

Code First annotations are a way of annotating the Code First model with any type of database metadata such that Migrations can detect differences in this metadata as the model evolves and can scaffold appropriate migrations for these changes. This can be coupled with extensions to the Migrations SQL generator such that SQL can be generated to update the database appropriately.

All the examples below use the model included at the end of this page.

The fluent API

To add an annotation for a table:

modelBuilder.Entity<Post>()
    .HasTableAnnotation("MyAnnotation", "MyData");

 

To add an annotation for a column:

modelBuilder.Entity<Post>()
    .Property(p => p.Title)
    .HasColumnAnnotation("MyAnnotation", "MyOtherData");

 

Any annotation can be cleared by passing null:

modelBuilder.Entity<Post>()
    .HasTableAnnotation("MyAnnotation", null);

 

You can also add annotations for tables and columns that are not directly mapped to properties or classes. For example, to add an annotation for a many-to-many join table:

modelBuilder.Entity<Post>()
    .HasMany(p => p.Tags)
    .WithMany(t => t.Posts)
    .Map(m => m.HasTableAnnotation("MyAnnotation", "MyData"));

 

To add an annotation for an FK in an independent association:

modelBuilder.Entity<Blog>()
    .HasMany(b => b.Posts)
    .WithRequired(p => p.Blog)
    .Map(m => m.MapKey("BlogId").HasColumnAnnotation("BlogId", "MyAnnotation", "MyData"));

Conventions

Similar APIs exist for Code First conventions. For example, to add an annotation to any column mapped from a property named “Title”:

modelBuilder.Properties()
    .Where(p => p.Name == "Title")
    .Configure(p => p.HasColumnAnnotation("MyAnnotation", "MyData"));

 

To add an annotation to any type starting with “B”:

modelBuilder.Types()
    .Where(t => t.Name.StartsWith("B"))
    .Configure(c => c.HasTableAnnotation("MyAnnotation", "MyData"));

Attributes

It is also possible to create a .NET attribute and couple it to a Code First convention such that putting the attribute onto an entity type or property will cause the corresponding table or column to be annotated.  For example, consider this attribute class:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = false)]
public class AnnotateMeAttribute : Attribute
{
    public string Data { get; set; }
}

 

Add a convention to use this attribute to create column annotations:

modelBuilder.Conventions.Add(
    new AttributeToColumnAnnotationConvention<AnnotateMeAttribute, string>(
        "MyAnnotation",
        (property, attributes) => attributes.Single().Data));

 

Or to create table annotations:

modelBuilder.Conventions.Add(
    new AttributeToTableAnnotationConvention<AnnotateMeAttribute, string>(
        "MyAnnotation",
        (entityType, attributes) => attributes.Single().Data));

 

Note that in the example above the attribute is marked with AllowMultiple = false which means the convention will only be called with exactly one attribute. If AllowMultiple = true is used, then the attributes list may contain one or more attribute instances which usually must be processed into a single annotation since a given table or column can only have one annotation with any given name. The TypeId property of the attribute will also need to be overwritten to return a different value for each instance because of the way .NET type descriptors handle attributes.

Scaffolding

Migrations will automatically detect changes in annotations and scaffold the appropriate migration operations. These operations may be:

  • AddColumnOperation when a new column is created it will contain annotation information
  • AlterColumnOperation when annotations on an existing column change
  • DropColumnOperation when an annotated column is dropped
  • AddTableOperation when a new table is created it will contain annotation information
  • AlterTableOperation when annotations on an existing table change
  • DropTableOperation when an annotated table is dropped

Annotation information in the migration is provided as a dictionary of annotation name to annotation values. For example:

public partial class Second : DbMigration
{
    public override void Up()
    {
        AlterColumn("dbo.Posts", "Title", c => c.String(
            annotations: new Dictionary<string, AnnotationValues>
            {
                {
                    "MyAnnotation",
                    new AnnotationValues(oldValue: "MyData", newValue: "MyOtherData")
                },
            }));
    }

    public override void Down()
    {
        AlterColumn("dbo.Posts", "Title", c => c.String(
            annotations: new Dictionary<string, AnnotationValues>
            {
                {
                    "MyAnnotation",
                    new AnnotationValues(oldValue: "MyOtherData", newValue: "MyData")
                },
            }));
    }
}

SQL generation

The default SQL generators do not do anything with annotation information. To actually generate SQL for the annotations it is necessary to replace or extend the MigrationSqlGenerator class for any database provider of interest. For example:

public class ExtendedSqlGenerator : SqlServerMigrationSqlGenerator
{
    protected override void Generate(ColumnModel column, IndentedTextWriter writer)
    {
        // Obtain annotation info
        AnnotationValues values;
        column.Annotations.TryGetValue("MyAnnotation", out values);

        // Do SQL generation for column using annotation value as appropriate
    }
}

 

The extended SQL generator should then be registered, either in the Migrations configuration:

internal sealed class Configuration : DbMigrationsConfiguration<BlogContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        SetSqlGenerator("System.Data.SqlClient", new ExtendedSqlGenerator());
    }
}

 

Or in the application’s DbConfiguration:

public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        SetMigrationSqlGenerator("System.Data.SqlClient", () => new ExtendedSqlGenerator());
    }
}

Non-string annotations

In all the examples above the annotation value is a simple string. This is the easiest thing to do, but annotation values can be of any type if necessary. However, since the annotations must be stored in the serialized form of the Code First model it is necessary to be able to serialize and de-serialize the value. This is done by creating a class that implements IMetadataAnnotationSerializer. For example, annotation with a CLR type would require something like this:

internal class ClrTypeAnnotationSerializer : IMetadataAnnotationSerializer
{
    public string Serialize(string name, object value)
    {
        return ((Type)value).AssemblyQualifiedName;
    }

    public object Deserialize(string name, string value)
    {
        return Type.GetType(value);
    }
}

 

And the serializer must be registering in the application’s DbConfiguration:

public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        SetMetadataAnnotationSerializer("Myannotation", () => new ClrTypeAnnotationSerializer());
    }
}

 

A code generator is also required if non-string types are to be scaffolded in the generated migrations. To do this, implement a class that extends from AnnotationCodeGenerator. For example:

public class ClrTypeCSharpCodeGenerator : AnnotationCodeGenerator
{
    public override void Generate(string annotationName, object annotation, IndentedTextWriter writer)
    {
        writer.Write("Type.GetType(\"" + ((Type)annotation).AssemblyQualifiedName + "\")");
    }
}

 

This annotation code generator must then be added to the overall Migrations code generator in the Migrations configuration:

internal sealed class Configuration : DbMigrationsConfiguration<BlogContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        CodeGenerator.AnnotationGenerators["MyAnnotation"] = () => new ClrTypeCSharpCodeGenerator();
    }
}

 

Unfortunately it is not possible to register the code generator in the application’s DbConfiguration.

The model

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int Id { get; set; }

    [AnnotateMe(Data = "MyData")]
    public string Title { get; set; }

    public string Content { get; set; }

    public virtual Blog Blog { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

Edited Issue: DbMigration.Sql fails when the word 'go' is contained in the text [2639]

$
0
0
If a DbMigration.Sql includes the word 'go' in an INSERT/UPDATE statement (for example), a 'Unclosed quotation mark..' exception will occur.

Can be reproduced in EF6.1.2 with the following

```
public override void Up()
{
// create table
Sql( "create table [SomeTable] (id int, msg nvarchar(max));");

// insert values
Sql( "insert into [SomeTable] (id, msg) values (1, 'click here to go to the next page');" );
}
```

I suspect this was introduced in https://entityframework.codeplex.com/SourceControl/changeset/a19438b6391085003046928d2e3cdbc55e3275ac


Commented Issue: DbMigration.Sql fails when the word 'go' is contained in the text [2639]

$
0
0
If a DbMigration.Sql includes the word 'go' in an INSERT/UPDATE statement (for example), a 'Unclosed quotation mark..' exception will occur.

Can be reproduced in EF6.1.2 with the following

```
public override void Up()
{
// create table
Sql( "create table [SomeTable] (id int, msg nvarchar(max));");

// insert values
Sql( "insert into [SomeTable] (id, msg) values (1, 'click here to go to the next page');" );
}
```

I suspect this was introduced in https://entityframework.codeplex.com/SourceControl/changeset/a19438b6391085003046928d2e3cdbc55e3275ac


Comments: Fixed in changeset 3207eb9347c2cfe706304b27c6e788a2843bbbec

Commented Issue: DbMigration.Sql fails when the word 'go' is contained in the text [2639]

$
0
0
If a DbMigration.Sql includes the word 'go' in an INSERT/UPDATE statement (for example), a 'Unclosed quotation mark..' exception will occur.

Can be reproduced in EF6.1.2 with the following

```
public override void Up()
{
// create table
Sql( "create table [SomeTable] (id int, msg nvarchar(max));");

// insert values
Sql( "insert into [SomeTable] (id, msg) values (1, 'click here to go to the next page');" );
}
```

I suspect this was introduced in https://entityframework.codeplex.com/SourceControl/changeset/a19438b6391085003046928d2e3cdbc55e3275ac


Comments: Cool, thanks for fixing!

Created Unassigned: "You have an error in your SQL syntax" after upgrading from EF 6.1.1 to 6.1.2 [2651]

$
0
0
After upgrading a Visual Studio 2013 MVC web project from EntityFramework 6.1.1 to 6.1.2, I get the following error from MySQL:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM ((SELECT
CASE WHEN (`Extent2`.`RoleId` IS NULL) THEN (NULL) ELSE (1) END' at line 31

The error is caught by the CookieAuthenticationProvider OnException callback in Startup.Auth.cs. I believe the query is triggered somewhere in the Microsoft Identity code.


app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MakeUserManager, MakeUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))),
OnException = context => { ErrorLogging.LogError("Make.Designer.Web.Startup.ConfigureAuth()", "An error occured while initializing the CookieAuthenticationProvider.", context.Exception); }
}
});

Edited Unassigned: "You have an error in your SQL syntax" after upgrading from EF 6.1.1 to 6.1.2 [2651]

$
0
0
After upgrading a Visual Studio 2013 MVC web project from EntityFramework 6.1.1 to 6.1.2, I get the following error from MySQL:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM ((SELECT
CASE WHEN (`Extent2`.`RoleId` IS NULL) THEN (NULL) ELSE (1) END' at line 31

The error is caught by the CookieAuthenticationProvider OnException callback in Startup.Auth.cs. I believe the query is triggered somewhere in the Microsoft Identity code.


```
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MakeUserManager, MakeUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))),
OnException = context => { ErrorLogging.LogError("Make.Designer.Web.Startup.ConfigureAuth()", "An error occured while initializing the CookieAuthenticationProvider.", context.Exception); }
}
});
```

New Post: Index column sort order

$
0
0
Currently one can set unique, clustered, and column order within an index. Is it going to be possible (or can you already) to set the sort order of the columns? Currently each column within an index is set to Ascending, but I wish to set a column sort order to be descending.

New Comment on "Code First Annotations"

$
0
0
Code First annotations won't work as described here. See this forum article for correction: https://social.msdn.microsoft.com/Forums/en-US/6319788d-4e7a-4aae-ab84-8efd51fc0ba5/how-can-i-have-custom-data-annotation-attribute-alter-the-target-of-a-migration?forum=adodotnetentityframework

New Post: Error only in shortcut network = The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

Commented Unassigned: "You have an error in your SQL syntax" after upgrading from EF 6.1.1 to 6.1.2 [2651]

$
0
0
After upgrading a Visual Studio 2013 MVC web project from EntityFramework 6.1.1 to 6.1.2, I get the following error from MySQL:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM ((SELECT
CASE WHEN (`Extent2`.`RoleId` IS NULL) THEN (NULL) ELSE (1) END' at line 31

The error is caught by the CookieAuthenticationProvider OnException callback in Startup.Auth.cs. I believe the query is triggered somewhere in the Microsoft Identity code.


```
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<MakeUserManager, MakeUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (id) => (Int32.Parse(id.GetUserId()))),
OnException = context => { ErrorLogging.LogError("Make.Designer.Web.Startup.ConfigureAuth()", "An error occured while initializing the CookieAuthenticationProvider.", context.Exception); }
}
});
```
Comments: I will see what I can do about capturing the full query myself.

Commented Unassigned: The underlying provider failed on Open. [2661]

$
0
0
Am Using MVC5 and Entityframework 6.1.2 Code Based Project. When I Try to Create DB It Throwing Error "the underlaying provider faild on Open"

My Self Used this Connection String

<add name="Conn" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\MyDB.mdf;Initial Catalog=MYDB;Integrated Security=True; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

How Can I Solve this Issue. I Refered "https://entityframework.codeplex.com/workitem/1156" this Link Already. But am Not Using any Migrations. Please any one Help Me The Issue.
Comments: i Commanded this Database.SetInitializer<HPRM_DataContext>(null); in My Code its Working Fine Thanks Guy's

Commented Unassigned: Query with multiple Includes does not work in 6.1.2 (working in 6.1.1) [2653]

$
0
0
We have a query that use many "Includes". The generated SQL Code is invalid.

We are using EF together with DevArt for Oracle. I could not confirm, that the same query will/will also not work with SQL Server.

The very same query works fine with Entity Framework 6.1.1.

I found a related issue here in the comments:
http://blogs.msdn.com/b/adonet/archive/2014/12/22/ef6-1-2-rtm-available.aspx#10584907
(also invalid SQL, multiple Includes and not SQL Server but MySql)
Comments: Exception is a OracleException. ({"ORA-00904: \"c\".\"C46\": invalid identifier"}) The generated sql code is broken. I have created a reproduce here: https://onedrive.live.com/redir?resid=9D87CECB1EA8118F!148718&authkey=!ADVo11Xjd9PFSdc&ithint=file%2czip If EF 6.1.2 is replaced 6.1.1 this example works fine.

Commented Unassigned: Visual Studio 2012 Professional and EF 6.1.1 [2608]

$
0
0
Hi Team,

This morning I stumbled to this weird problem. Everytime I tried to add New Connection, it always throw "Exception has been thrown by the target of an invocation".

The steps to reproduce the error is shown in my blog: [http://sodeve.net/2014/12/visual-studio-2012-professional-entity-framework-6-1-1-error-exception-thrown-target-invocation/](http://sodeve.net/2014/12/visual-studio-2012-professional-entity-framework-6-1-1-error-exception-thrown-target-invocation/)

I've checked the Event viewer, nothing there. I even run the VS with logging, but no error logs generated.

Anyway, I resorted back to EF 6.0.0 which makes the problem go away.

Thank you for looking into this.
Comments: I am using visual studio 2013 entity framework 6 with entityframework sqlserverCompact 4.0 and I am also getting the error. I also set the exception to everything and nothing comes up except for the Cannot load exception has been throws by the target of an invocation when clicking on the edmx file and trying to load the designer. I created the edmx file by right clicking the sdf database under sql server compact/sqllite toolbox and clicked generate code (ef/linq) => then clicking add entity data model to current project. It creates all the files but when you click on it the error comes up.
Viewing all 10318 articles
Browse latest View live




Latest Images