Readonly table/entity EF Core 3.0

Viewed 740

Is it possible to make a table/entity in EF Core 3.0? Basically i have history tables on which i want to ristrict insert/update/delete commands.

I already tried AsNoTracking by changing:

public DbSet<SampleHistory> SampleHistories { get; set; }

to:

public IQueryable<SampleHistory> SampleHistories { get {return Set<SampleHistory>).AsNoTracking<SampleHistory>(); } }

It works fine if i do something like this (nothing gets saved in DB):

var v = DbContext.SampleHistories.FirstOrDefault(e => e.HistoryId == 1);
v.Field1 = $"Test{DateTime.Now.ToLongTimeString()}";
DbContext.SaveChanges();

but if i add Update statment before save, i see record getting updated in DB:

var v = DbContext.SampleHistories.FirstOrDefault(e => e.HistoryId == 1);
v.Field1 = $"Test{DateTime.Now.ToLongTimeString()}";
DbContext.Update(v);
DbContext.SaveChanges();

I want to avoid that too.

1 Answers

I solved this requirement by enforing such tables to get generated as Views.

Ex:

modelBuilder.Entity<SampleHistory>(eb =>
        {
            eb.HasNoKey();
            eb.ToView("Sample_History");
        .
        .
        .
        });

EF thows Invalid operation exception if you try to perform Insert, Update, or Delete operation on such tables.

Related