I write class contents to base through EF, I describe through Code First.

public class LogRecord { [Key] public int Id { get; set; } public virtual LogDelivery LogDelivery {get;set;} } public class LogDelivery { public int Id { get; set; } public int LogRecordId { get; set; } public new ICollection<LogOrder> Orders { get; set; } public new ICollection<LogPrintedDoc> ResignDocs { get; set; } [Required] public virtual LogRecord LogRecord { get; set; } } 

Further other attachments are described (LogOrder, LogPrintedDoc, etc.) For one-to-many connections, for example for a Delivery-Order connection, everything works fine, the parent Id is specified.
For one-to-one communication, i.e. for a Record-Delivery connection, a 0 is always written to the Delivery table in the RecordId field.

Question: what is wrong? How to make EF write RecordId to the database?

  • EF writes to the database what you put into the object. If you have LogDelivery.Id == 0 , then 0 will be recorded - ixSci
  • Id is a key, EF created it as an Identity-field, by itself I can not assign it. If I understand everything correctly, then when I assign LogRecord.Delivery to a certain value, I must form a connection between the records in the LogRecord and LogDelivery tables. This is how it works in relation to 1-to-many communication. Those. when I fill in Delivery.Orders, I do SaveChanges - I create entries in Orders with a link to the corresponding Delivery in the DeliveryId field. But in the case of the One-to-One ID of the parent in the database is not written. Although when creating the scheme, EF created all the necessary keys and constraints. - Zufir
  • Those. in the LogDelivery Id table is the foreign key? EF did that? Something I strongly doubt it, moreover, this field should not be Identity - ixSci

1 answer 1

In the understanding of EF, a one-to-one relationship is (by default) a primary key relationship. The LogRecordId property LogRecordId not used for communication - and therefore it is always 0 (you do not fill it in).

If you are satisfied with this situation - just delete LogRecordId . Otherwise, you will have to explain to EF what exactly you had in mind:

  protected override void OnModelCreating(DbModelBuilder builder) { builder.Entity<LogDelivery>().HasRequired(x => x.LogRecord).WithOptional(x => x.LogDelivery).Map(c => c.MapKey("LogRecordId")); } 
  • LogRecordId will have to be deleted anyway - EF seems to create this property when mapping and swears that it already exists. For the rest, it worked, and FK was registered correctly. - Zufir