Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

validation - Entity Framework IValidatableObject reference DbContext

I'm trying to get EF 4.1 working with Repository, UnitOfWork, separation of entities from EF and validation.

I followed this guide to get a nice separation of my POCO entities from the EF model and I'm now following this guide to implement validation (with IValidatableObject).

My solution consists of:

  • Contacts.Repository [references EF and Contacts.Entities]:
    • Contacts.edmx
    • ContactsDbContext.cs
  • Contacts.Entities [no references]:
    • Contact.cs (Contacts.Entities.Contact partial class)
  • Contacts.Validation [references Contacts.Entities and Contacts.Repository]
    • Contact.cs (Contacts.Entities.Contact partial class)

But I'm hitting a brick wall with the validation:

  1. I cannot add validation logic to Contacts.Entities because it would cause a circular reference with Contacts.Repository (contact.Validate(...) needs to use ContactsDbContext). So I created a separate Contacts.Validation project.
  2. But, this means splitting the Contact class with partial classes to define Contact inside both Contacts.Entities and Contacts.Validation. The code no longer compiles because you can't define a partial class accross different assemblies.

Anyone got any pointers for me here? I've posted the code below...

Contacts.Repository.ContactsDbContext.cs:

namespace Contacts.Repository
{
  public partial class ContactsDbContext : DbContext
  {
    public DbSet<Contact> Contacts { get; set; }

    protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
    {
      items.Add("Context", this);
      return base.ValidateEntity(entityEntry, items);
    }
  }
}

Contacts.Entities.Contact.cs:

namespace Contacts.Entities
{
    public partial class Contact
    {
        public string Name { get; set; }
    }
}

Contacts.Validation.Contact.cs contains:

namespace Contacts.Entities
{
  public partial class Contact : IValidatableObject
  {
      public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
      {
          ContactsDbContext contacts = (ContactsDbContext)validationContext.Items["Context"];

          //Check if Contact already exists with the same Name
          if (contacts.Any<Contact>(c => c.Name == this.Name))
            yield return new ValidationResult("Contact 'Name' is already in use.", new string[] { "Name" });

          yield break;
      }
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Technically you could introduce an interface with an explicit implementation like so:

In Contacts.Entities assembly:

public interface IContactsDbContext
{
    IQueryable<Contact> Contacts { get; }
    // Not DbSet<Contact> because you don't want dependency on EF assembly 
}

//...

public class Contact : IValidatableObject // No partial class anymore
{
    public string Name { get; set; }

    public IEnumerable<ValidationResult> Validate(
        ValidationContext validationContext)
    {
        IContactsDbContext context = 
            validationContext.Items["Context"] as IContactsDbContext;

        if (context.Contacts.Any<Contact>(c => c.Name == this.Name))
            yield return new ValidationResult(
                "Contact 'Name' is already in use.", new string[] { "Name" });

        yield break;
    }
    // IValidatableObject, ValidationResult and ValidationContext is in
    // System.ComponentModel.DataAnnotations.dll, so no dependency on EF
}

In Contacts.Repository assembly (references Contacts.Entities assembly):

public class ContactsDbContext : DbContext, IContactsDbContext
{
    public DbSet<Contact> Contacts { get; set; }

    IQueryable<Contact> IContactsDbContext.Contacts // explicit impl.
    {
        get { return Contacts; } // works because DbSet is an IQueryable
    }

    protected override DbEntityValidationResult ValidateEntity(
        DbEntityEntry entityEntry, IDictionary<object, object> items)
    {
        items.Add("Context", this);
        return base.ValidateEntity(entityEntry, items);
    }
}

Contacts.Validation assembly can be removed.

However, I do not really like this solution. Your POCO has - through the Validate method - still a dependency on the repository, if interface or not. For a stronger separation of concerns I would probably prefer to have a separate Validation class which does perhaps also operations on the repo. Or if I would implement IValidatableObject I would probably only do validations which depend on model object properties alone (things like "production date must not be later than shipping date" and so on). Well, it's partially a matter of taste. The second example you have linked does not really care about separation of concerns, so you have somehow a conflict with the first example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...