I have long been stuck in this problem. I am using the Fluent API Code-First to create a database (EF 6.1). The problem is that when I add a new object, I can access the objects in this object by the navigation property, but FK is 0 or NULL (if necessary and optionally, respectively). This is a one-to-one relationship, and I tried both bidirectional and unidirectional.
The following is part of the code (simplified, but only by including smaller objects):
public class Template
{
public int Id { get; set; }
public int XmlDocId{ get; set; }
public virtual XmlDoc XmlDoc { get; set; }
public int? OtherXmlDocId{ get; set; }
public virtual OtherXmlDoc OtherXmlDoc { get; set; }
}
public class XmlDoc
{
public int Id { get; set; }
[Required]
public string RawXml { get; set; }
}
public class OtherXmlDoc
{
public int Id { get; set; }
[Required]
public string RawXml { get; set; }
}
public class MyDbContext
{
public virtual DbSet<Template> Templates { get; set; }
public virtual DbSet<XmlDoc> XmlDocs { get; set; }
public virtual DbSet<OtherXmlDoc> OtherXmlDocs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
ConfigureTemplates(modelBuilder);
}
private void ConfigureTemplates(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Template>()
.HasRequired<XmlDoc>(c => c.XmlDoc)
.WithRequiredPrincipal()
.WillCascadeOnDelete(true);
modelBuilder.Entity<Template>()
.HasOptional<OtherXmlDoc>(c => c.OtherXmlDoc)
.WithOptionalPrincipal()
.WillCascadeOnDelete(true);
}
}
, , (FK ..). , , , XmlDocId
0, (XmlDoc
Id
3. OtherXmlDocId
OtherXmlDoc
, Id null. :
public void Add(string xmlString1, string xmlString2)
{
XmlDoc firstDoc = new XmlDoc { rawXml = xmlString1 };
OtherXmlDoc secondDoc = new OtherXmlDoc { rawXml = xmlString2 };
var entity = new Template
{
XmlDoc = firstDoc,
OtherXmlDoc = secondDoc
}
context.Templates.Add(entity);
context.SaveChanges();
}
. , , . , - :). !
EDIT โโ. , , XmlDocId
OtherXmlDocId
0/null, , Id. , , SaveChanges()
, EF , FK (Source).
EDIT II. "" , FK , SaveChanges()
(Template.XmlDocId = Template.XmlDoc.Id
), , , , . EF, .