Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Multiple one to one relationships #4920


User avatar
0
manojreddy created

I am trying to create a model that has a Customer entity with two references to Address entities: BillingAddress and ShippingAddress.

Customer

public class Customer
{
    public Guid CustomerId {  get;set;}

    public Guid? BillingAddressId { get; set; }
    public Address BillingAddress { get; set; }

    public Guid? ShippingAddressId { get; set; }
    public Address ShippingAddress { get; set; }
}

Address

public class Address
{
    public Guid AddressId { get; set; }

    public Customer Customer { get; set; }
    public Guid CustomerId { get; set; }
}

OnModelCreating

modelBuilder.Entity<Address>(eb =>
{
    eb.HasOne(e => e.Customer).WithOne(o => o.BillingAddress).OnDelete(DeleteBehavior.Cascade);
});

modelBuilder.Entity<Address>(eb =>
{
    eb.HasOne(e => e.Customer).WithOne(o => o.ShippingAddress).OnDelete(DeleteBehavior.Cascade);
});

I get the following error when trying to create the migration:

Can not]Cannot create a relationship between 'Customer.ShippingAddress' and 'Address.Customer', because there already is a relationship between 'Customer.BillingAddress' and 'Address.Customer'. Navigation properties can only participate in a single relationship.[/quote]

I'm trying to configure the model so that when the Customer is deleted the referenced Addresses are deleted as well. I would like to be able to do this without loading the Addresses into the Context and relying on the database to cascade.


4 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    @ManojReddy I think you need to remove Customer reference from Address.

  • User Avatar
    0
    manojreddy created

    Thanks for response, but I don’t think that it should work

  • User Avatar
    0
    bbakermmc created

    Whats the point of the address table if you only have a 1 to 1 relationship?

    Address should return a collection of Customers.

  • User Avatar
    0
    alper created
    Support Team

    <cite>BBakerMMC: </cite> Whats the point of the address table if you only have a 1 to 1 relationship?

    Address should return a collection of Customers.

    Yeap you'r right. Actually it's a value object. <a class="postlink" href="https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects">https://docs.microsoft.com/en-us/dotnet ... ue-objects</a>