Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a sql reserved keyword in the name of a property in an entity framework data context?

The following code throws the exception "EntitySqlException: 'Group' is a reserved keyword and cannot be used as an alias, unless it is escaped. Near line 1, column 11".

My question is firstly why is there any relation between the name of the collection I choose on my data context and, seeminlgy the sql query that is generated?

And secondly, is there anything I can do, besides renaming the property on my context, to resolve it (I know the name is stupid, there are reasons why I cannot change the name, much as I would like to, that I won't go into here)?

Is there something I can do with the modelBuilder perhaps?

public class GroupEntity
{
    public int GroupEntityId { get; set; }
    public string Name { get; set; }
}

public class MyContext : DbContext
{
    public MyContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
    {
        Group = Set<GroupEntity>();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<GroupEntity>().ToTable("GroupEntities");
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<GroupEntity> Group { get; private set; }
}

//...
using (var ctx = new MyContext("valid connection string"))
{
    var e = ctx.Group.Count(a => a.GroupEntityId % 2 == 0);
    // Exception thrown here
    Console.WriteLine(e);
}
like image 622
kmp Avatar asked Mar 09 '12 09:03

kmp


People also ask

What is the use of DbContext in Entity Framework?

A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.

Which method is used to add a DbContext to an application?

The OnConfiguring() method allows us to select and configure the data source to be used with a context using DbContextOptionsBuilder . Learn how to configure a DbContext class at here.

How do I use Find in Entity Framework?

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.


1 Answers

This is fixed in EF 4.3.1 and EF 5.0 beta1. Please use NuGet to update the EntityFramework package to the latest version. For example, in the Package Manager Console, run:

Update-Package EntityFramework
like image 161
Arthur Vickers Avatar answered Sep 21 '22 01:09

Arthur Vickers