Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly table/entity EF Core 3.0

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.

like image 984
SKS Avatar asked Nov 07 '22 05:11

SKS


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.

like image 108
SKS Avatar answered Dec 09 '22 20:12

SKS