Search code examples
c#.netpococode-firstentity-framework-4.3

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);
}

Solution

  • 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