Matt Whetton
Matt Whetton

Reputation: 6786

Navigation property without referential integrity constraint in Entity Framework 6

In EF 6 (code first), is it possible to have a navigation property set-up without enforcing a referential integrity constraint?

For example:

public class Person{

    public IList<Pet> Pets { get; set; }

}

public class Pet{

    public int OwnerId { get; set; }
    public Person Owner { get; set; }

}

So in the example above I'd like to be able to add a Pet with an OwnerId, even if that owner does not exist in the Owners table.

Thanks

Matt

Upvotes: 3

Views: 740

Answers (2)

Claies
Claies

Reputation: 22323

You can define the relationship using the fluent API.

modelBuilder.Entity<Pet>
    .hasOptional(p => p.Owner)
    .willCascadeOnDelete(false);

This will configure the relational property as optional, and will ensure that cascade delete does not take effect. You can create a Pet without an Owner, and deleting an Owner will not delete the associated Pets.

However you cannot assign Pet.OwnerId to an OwnerId that doesn't exist in the Owner table. If you truly need to have some way of tracking invalid OwnerId values, you either need to have a separate property which you manually update with an arbitrary value, or you would need to define these objects without using a navigation property, and perform your lookups manually.

It would be an exceptional situation where you would need to supply an arbitrary value for OwnerId that doesn't match the Owner table; In 99% of all cases, an optional relationship which accepts a valid OwnerId or null is all that is necessary.

The OwnerId property isn't actually necessary on the Pet object, but if it is present, it should be set to int? to be nullable.

Upvotes: 3

Michal Ciechan
Michal Ciechan

Reputation: 13898

Short Answer: Don't use EF. The whole point of Object Relational Mappers is to ensure you have valid data as well as help with retrieving/persisting it

All you really want is some sort of mapper.

Long Answer: Curious myself

Upvotes: -1

Related Questions