I am new to EF6 and fluent API, but I really tried all the possibilities before trying to bother you here but I am kind of stuck now.
I have the following model:
public class Event
{
public int Id { get; set; }
[Required]
public string Label { get; set; }
}
public class Address
{
public int Id { get; set; }
[Required]
public String City { get; set; }
}
Here's what I am trying to do:
- The event should have a required field
Address - The address can be used in an event or in another class (let's call it
Personfor example). Therefore, it shouldn't be directly be bound to theEventclass - When deleting an
Event(orPerson), I want to cascade and delete the linkedAddress
I tried many possibilities in Fluent API by looking at the documentations and searching on the net. Despite that, I kept having various issues: conflicting multiplicities, inconsistent model or not being able to cascade on delete.
Could someone please help? I am really stuck! :)
Thank you!
!!!UPDATE!!! As requested, here's the best solution I could find:
public class Event
{
public int Id { get; set; }
[Required]
public string Label { get; set; }
[Required]
public virtual Address.Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
[Required]
public String City { get; set; }
}
And the fluent code as follows:
modelBuilder.Entity<Event>()
.HasRequired(e => e.Address)
.WithOptional()
.Map(e => e.MapKey("AddressId"))
.WillCascadeOnDelete(true);
This implementation adds a foreign key in the Event table to the Address table. However, the cascade on delete will work in the following direction: deleting the Address will delete the Event. Unfortunately, I am trying to accomplish the opposite: I want the Address to be deleted only when the Event is!
Thank you again :)
Your requirements are fighting each other.
Addressshould be deleted when anEventis, theEventmust be the principal (the entity to which a foreign refers).Address, the other classes should refer toAddress, which makesAddressthe principal.There is an alternative.
Addresscould have two foreign keys, toPersonand toEvent. But this is not very appealing, because the keys must both be nullable and there is no database constraint to enforce that they are mutually exclusive.Another alternative is to make
Addressa complex type, so both theEventand thePersontables will have all address columns. Of course this is not well normalized, and you can't handleAddressesas separate entities, but at least there is no cascade issue, because an address is part of theEventrecord.I think your best option is to have several classes refer to
Addressand write logic to delete orphan addresses.