2

I have the following BaseEntity

public class BaseEntity
{
    public BaseEntity()
    {
        DateCreated = DateTime.UtcNow;
        DateModified = DateTime.UtcNow;
    }

    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }

    [MaxLength(36)]
    public string CreateUserId { get; set; }

    [MaxLength(36)]
    public string ModifyUserId { get; set; }
}

All my other entities derive from it. Now I'd like to use fluent configuration instead of the DataAnnotations. Do I really have to configure the MaxLength of the two string properties in every single DbModelBuilder configuration?

1 Answer 1

7
+50

Do I really have to configure the MaxLength of the two string properties in every single DbModelBuilder configuration?

No. You can configure base type validations and EF will apply them on derived types. For example:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<BaseEntity>().Property(x => x.CreateUserId).HasMaxLength(36);
    modelBuilder.Entity<BaseEntity>().Property(x => x.ModifyUserId).HasMaxLength(36);

    base.OnModelCreating(modelBuilder);
}

Update (as per your comment):

You can use the (rather new) Properties() method to define mapping and validations based on property names rather than on entity types.

For example:

modelBuilder.Properties().Where(x => x.Name == "CreateUserId").Configure(x => x.HasMaxLength(36));
modelBuilder.Properties().Where(x => x.Name == "ModifyUserId").Configure(x => x.HasMaxLength(36));

See MSDN

Sign up to request clarification or add additional context in comments.

8 Comments

Yes, but I want to get rid of the DataAnnotation
Now I get an Exception that BaseEntity has no key defined.
@Sandro, See my revision. I added Ignore<BaseEntity>(). Assuming you do have keys defined for your derived types, it should work just fine.
Now I'm back to varchar(max) for these fields because BaseEntity is ignored on model creation
If you'll go C# 6, you'll be able to avoid the "magic strings" using the nameof operator.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.