Efcore: Improve the exception message when altering a read-only model

Created on 26 May 2019  Â·  7Comments  Â·  Source: dotnet/efcore

Problem

I have a method for change table name dynamically

```c#
private static RelationalEntityTypeAnnotations GetRelationalEntityType(this DbContext dbContext, Type type)
{
return dbContext.Model.FindEntityType(type).Relational() as RelationalEntityTypeAnnotations;
}

    public static void ChangeTable(this DbContext dbContext, Type type, string tableName)
    {

        var relational = dbContext.GetRelationalEntityType(type);
        if (relational != null)
        {
            relational.TableName = tableName;
        }
    }

    public static DbSet<TEntity> ChangeTable<TEntity>(this DbSet<TEntity> dbSet, string tableName) where TEntity : class
    {
        var dbContext = dbSet.GetService<ICurrentDbContext>().Context;
        dbContext.ChangeTable(typeof(TEntity), tableName);
        return dbSet;
    }
the above code work fine in 2.X

but in 3.0 preview5 will throw an exception

System.NullReferenceException : Object reference not set to an instance of an object.
堆栈跟踪:
在 EntityType.OnAnnotationSet(String name, Annotation annotation, Annotation oldAnnotation)
在 Annotatable.SetAnnotation(String name, Object value)
在 RelationalAnnotations.SetAnnotation(String annotationName, Object value)
在 RelationalEntityTypeAnnotations.set_TableName(String value)
在 DbExtensions.ChangeTable(DbContext dbContext, Type type, String tableName) 在 DbExtensions.cs 行: 39
在 DbExtensions.ChangeTableTEntity 在 DbExtensions.cs 行: 30
在 DbExtensionsTest.ChangeTable_SqlServer() 在 DbExtensionsTest.cs 行: 23
在 DbExtensionsTest.ChangeTable_SqlServer() 在 DbExtensionsTest.cs 行: 31
在 --- End of stack trace from previous location where exception was thrown ---
```

Further technical details

EF Core version:3.0.0-preview5.19227.1
Database Provider: Microsoft.EntityFrameworkCore.SqlServer or Npgsql.EntityFrameworkCore.PostgreSQL
Operating system: Windows 10
IDE: Visual Studio 2019 16.2.0 Preview 1.0

customer-reported punted-for-3.0 type-enhancement

Most helpful comment

@MonkSoul no solution in EFCore
but you can try linq2db.EntityFrameworkCore
linq2db

Thank you very much for your answers and solutions, but I don't want to integrate database operation library any more, because I have written an ef core extension: https://gitee.com/monksoul/Fur

All 7 comments

@darkflame0 Can you show an example of how you are using this code?

@darkflame0 Can you show an example of how you are using this code?

@ajcvickers
this is my test
```C#
[Fact]
public async Task ChangeTable_SqlServer()
{
var builder = new DbContextOptionsBuilder();
builder.UseSqlServer(@"Data Source=(localdb)MSSQLLocalDB;Initial Catalog=LiveChatDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
var db = new LiveChatDbContext(builder.Options);
try
{
var t = await db.Database.EnsureCreatedAsync();
//an exception was throwed
Assert.Throws(() => db.ChatMessage.ChangeTable("AnotherTable"));
Assert.True(await db.ChatMessage.EnsureTable());
var entity = new ChatMessage();
await db.ChatMessage.AddAsync(entity);
Assert.Equal(1, await db.SaveChangesAsync());
//but table name was changed successfully
Assert.True(await db.ChatMessage.FromSqlRaw("select * from AnotherTable").AnyAsync());

        }
        finally
        {
            await db.Database.EnsureDeletedAsync();
        }
    }

```

@darkflame0 Altering the model outside of OnModelCreating is not supported. It only worked by accident before 3.0

@AndriySvyryd i think it is a good feature TOT

I encountered the same problem in. Net 5.0.0 RC1. Do you have a solution now?

@MonkSoul no solution in EFCore
but you can try linq2db.EntityFrameworkCore
linq2db

@MonkSoul no solution in EFCore
but you can try linq2db.EntityFrameworkCore
linq2db

Thank you very much for your answers and solutions, but I don't want to integrate database operation library any more, because I have written an ef core extension: https://gitee.com/monksoul/Fur

Was this page helpful?
0 / 5 - 0 ratings