Entity Framework Core 7 - Saving entities with child entities that already exists using a different key

19 views Asked by At

I'm using Entity Framework Core 7. My entities have both an ID and a UUID and I've configured the entities with the UUID being the primary key and the ID as the foreign key.

I'm trying to find a way to save an entity with an existing child entity in the database using its UUID for the relationship.

For example, I have the Order and Product entity as follows:

public class Order
{
    public long ID { get; set; }
    public string? UUID { get; set; }
    public string Name { get; set; }
    public Product Product { get; set; }
}

public class Product
{
    public long ID { get; set; }
    public string? UUID { get; set; }
    public string Name { get; set; }
}

Suppose I already have the following product saved in the database:

{
    UUID: "XYZ",
    ID: 1,
    Name: "Prod-1"
}

From my front end I'd like to be able to send the following object to save a new order by linking it to the existing product via its UUID.

{
    Name: "Order-1",
    Product: {
    UUID: "XYZ"
    }
}

Is there any way to make EF understand this? I know my biggest problem is that I'm using the ID as the foreign key and not the UUID itself, but I'd like to know if there's any way around it.

0

There are 0 answers