Entity Framework 1 to 1?

I have a scenario where I optimally need a connection from 1 to 1 between two objects. I can do this with EF, but the end result is a model in which I cannot insert any data since the Entity Framework does not know which one should be inserted first. The same thing happens even if I change the ratio from 0..1 to 0..1.

Take an example. I have a File object and a FileData strong> object . A file must always have FileData and FileData must always have a link to the file. I do not want them to be in the same entity (table), because FileData can become quite large, and I basically need things from the entity file.

I would like to specify delete in the cascade between them so that if I delete the file, the associated FileData will also be deleted.

I would also like to be able to embed them as in one transaction, so that I could write

new File { FileData = ...

So, what would you prefer as a solution with Entity Framework? At the moment, I have added the relation only to the file. Thus, I can send both objects to the database with one save, but I don’t get the deletion in the cascade, since the main record is FileData, and this cascade works “incorrectly” in my use case.

+4
source share
1 answer

To configure a 1-1 connection, you must configure it this way

// Configure FirstClassID as PK for SecondClass
    modelBuilder.Entity<SecondClass>()
        .HasKey(m => m.FirstClassId);

    // Configure FirstClassId as FK for SecondClass
    modelBuilder.Entity<FirstClass>()
                .HasRequired(m => m.SecondClass) 
                .WithRequiredPrincipal(m => m.FirstClass); 

, FirstClassId primaryKey , , .. SecondClass

,

+4

Source: https://habr.com/ru/post/1654670/


All Articles