Question

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);
}
Was it helpful?

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

OTHER TIPS

So after a while of looking at this I have concluded that the answer to my question is that it is not possible.

This is not a massive deal, since I can rename the property, but I think it is something that should "just work" and so I raised an MS connect issue for it that can be found here: Using a sql reserved keyword as the name of a collection on a DbContext causes an exception. If this gets resolved or rejected because it is actually possible I will update this answer.

You can always make it plural, like Groups to make it a "non-reserved" word.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top