我需要在不知道其PK的情况下插入新实体。父实体还有另一个属性,它是GUID并且是唯一的,这是我们用于跨数据库引用的东西,这就是我所拥有的全部。我过去曾经做过,但是找不到有关如何再次做的参考。
[Table("School")]
public class SchoolEntity
{
public SchoolEntity()
{
Students = new HashSet<StudentEntity>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public Guid ExternalId { get; set; }
[ForeignKey("SchoolId")]
public virtual ICollection<StudentEntity> Students { get; set; }
}
[Table("Student")]
public class StudentEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public SchoolEntity School { get; set; }
}
//ExternalId won't work cause is not the primary key.
var school = new School { ExternalId = Guid.Parse('68e05258-550a-40f3-b68a-5d27a0d825a0') };
context.Attach(school);
context.Schools.Add.Add(new Student());
context.SaveChanges();
答案 0 :(得分:2)
好吧,需要引用实体的PK,以便正确设置引用实体的FK。
如果您没有它,显然您应该根据所拥有的(在您的情况下为辅助标识符)找到它(从数据库中获取)。例如:
var school = context.Schools.Single(e => e.ExternalId == externalId);
var student = new Student { School = school, ... };
context.Students.Add(student);
context.SaveChanges();
没有获取就无法使它正常工作的方法。如果您不想获取整个引用的实体(并且您确定它不会被上下文跟踪),则可以仅获取PK和Attach
一个存根实体:
var schoolId = context.Schools.Where(e => e.ExternalId == externalId)
.Select(e => e.Id).Single();
var school = new School( Id = schoolId);
context.Attach(school);
// ...