Paolo B
Paolo B

Reputation: 3364

Ensure at least one address added to database - Entity Framework Code First

I am just doing a demo project and would like to ensure at least one address is added to database for a person. To clarify - A person can have a Home address and/or a work address, but must have at least one of these.

Having difficulting deciding if needs to be done in EF Code First or code - Is it best to do this with Navigation properties or Fluent API - or is this something better suited to do in code as validation, e.g. adding ModelState.AddModelError

I know how to include relationship as one to one or zero (optional) - but in this case I would like person to must have either Home or Work address, or both.

What I have at moment in my Models:

public class Person
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public Address HomeAddress { get; set; }

    public Address WorkAddress { get; set; }
}

public class Address
{

    public string Street { get; set; }

    public string City { get; set; }

    public string County { get; set; }

    public string PostCode { get; set; }
}

Upvotes: 2

Views: 483

Answers (1)

user449689
user449689

Reputation: 3154

One approach you can use is implementing IValidatableObject, it will allow you to add your custom server side validation:

IValidatableObject is an interface that lives in System.ComponentModel.DataAnnotations. While it is not part of the Entity Framework API, you can still leverage it for server-side validation in your Entity Framework classes. IValidatableObject provides a Validate method that Entity Framework will call during SaveChanges or you can call yourself any time you want to validate the classes.

For more information have a look here

A simple implementation can look like this:

public class Person : IValidatableObject 
 { 
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public Address HomeAddress { get; set; }

    public Address WorkAddress { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
        if (HomeAddress == null && WorkAddress == null) 
        { 
            yield return new ValidationResult 
              ("At least one between the home and work address must be set", new[] { "HomeAddress", "WorkAddress" }); 
         } 
    } 
}

Upvotes: 3

Related Questions