Reputation: 89
I am using EntityFramework Core to connect to database in .Net core web API. I am facing issue while trying validate the entity before submit changes to DB i.e Context.SaveChanges(). Validation error is not thrown even though entity is not meeting specific condition. If i add the condition using attribute it work, but it is not working when conditions are added using Model build.
Is there way to properly validate entity which are created using Model builder?
Entity:
public class AppSession
{
public AppSession()
{
}
public long AppSessionId { get; set; }
public Guid ExternalAppSessionId { get; set; }
public DateTime CreatedDate { get; set; }
public Sources SourceId { get; set; }
public string Gcid { get; set; }
//[StringLength(60)]
public string UserAgent { get; set; }
public string SessionReferrer { get; set; }
}
Model Builder:
public class AppSessionConfig : IEntityTypeConfiguration<AppSession>
{
public void Configure(EntityTypeBuilder<AppSession> builder)
{
builder.Property(e => e.AppSessionId).HasColumnName("AppSessionID");
builder.Property(e => e.ExternalAppSessionId).HasColumnName("ExternalAppSessionID");
builder.Property(e => e.Gcid)
.HasColumnName("GCID")
.HasMaxLength(200)
.IsUnicode(false);
builder.Property(e => e.Keyword)
.HasMaxLength(255)
.IsUnicode(false);
builder.Property(e => e.SessionReferrer)
.HasMaxLength(512)
.IsUnicode(false);
builder.Property(e => e.SourceId).HasColumnName("SourceID");
builder.Property(e => e.UserAgent)
.HasMaxLength(50)
.IsUnicode(false);
}
Context:
public partial class TestDbContext : DbContext,IDbContext
{
public TestDbContext(DbContextOptions<TestDbContext> options)
: base(options)
{ }
public virtual DbSet<Entities.AppSession> AppSessions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new AppSessionConfig());
}
public override int SaveChanges()
{
ValidateEntities();
return base.SaveChanges();
}
private void ValidateEntities()
{
var entities = (from entry in ChangeTracker.Entries()
where entry.State == EntityState.Modified || entry.State == EntityState.Added
select entry.Entity);
var validationResults = new List<ValidationResult>();
foreach (var entity in entities)
{
var validationContext = new ValidationContext(entity);
Validator.ValidateObject(entity, validationContext, true);
}
}
}
Thanks,
Upvotes: 2
Views: 12822
Reputation: 5027
Not quite sure this is what you want, but there is some information here on validating an entity (client side) prior to saving to the database...
Upvotes: 1
Reputation: 327
EF Core doesn't make validation anymore.
There is post here with the same issue : Entity Framework Core doesn't validate data when saving?
Upvotes: 3