@David Thielen, Welcome to Microsoft Q&A,
Read-only properties in a model class. To enforce no setting on an insert and no changing on an update.
For your first question, I recommend that you could use IProperty.AfterSaveBehavior Property and IProperty.BeforeSaveBehavior Property to the read-only property.
Here is a code example you could refer to.
#nullable disable
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class StuContext:DbContext
{
public DbSet<Student> Students { get;set;}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string str = "connstr";
optionsBuilder.UseSqlServer(str);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().Property(m => m.Name).HasDefaultValue("defaultname").Metadata.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore);
modelBuilder.Entity<Student>().Property(m => m.Name).HasDefaultValue("defaultname").Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
}
}
After code first, if we want to insert a record with Name or change name from one record, it will not change the name.
Insert data
StuContext context = new StuContext();
Student student = new Student();
//var student = (from m in context.Students
// where m.Name == "defaultname"
// select m).FirstOrDefault();
student.Name = "test1";
student.Description = "d3";
context.Students.Add(student);
context.SaveChanges();
Update data:
StuContext context = new StuContext();
var student = (from m in context.Students
where m.Name == "defaultname"
select m).FirstOrDefault();
student.Name = "test1";
context.SaveChanges();
We can find that the database data could not be changed and only could be set to be default value.
Eliminate the non-nullable warning (and likely soon to be error) for EF model class properties.
For your second question, as you mentioned, it may be the best way to use #nullable disable
for ef classes.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.