http://msdn.microsoft.com/en-US/data/jj591620#RequiredToRequired上的示例代码是否正确?代码要求在Instructor类上使用OfficeAssignment prop。由于显而易见的原因,它无法解决。现在在ef上建立一对一关系的正确方法是什么?
// Configure the primary key for the OfficeAssignment
modelBuilder.Entity<OfficeAssignment>()
.HasKey(t => t.InstructorID);
modelBuilder.Entity<Instructor>()
.HasRequired(t => t.OfficeAssignment)
.WithRequiredPrincipal(t => t.Instructor);
public class OfficeAssignment
{
// Specifying InstructorID as a primary
[Key()]
public Int32 InstructorID { get; set; }
public string Location { get; set; }
// When the Entity Framework sees Timestamp attribute
// it configures ConcurrencyCheck and DatabaseGeneratedPattern=Computed.
[Timestamp]
public Byte[] Timestamp { get; set; }
// Navigation property
public virtual Instructor Instructor { get; set; }
}
public class Instructor
{
public Instructor()
{
this.Courses = new List<Course>();
}
// Primary key
public int InstructorID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public System.DateTime HireDate { get; set; }
// Navigation properties
public virtual ICollection<Course> Courses { get; private set; }
}
答案 0 :(得分:1)
本地/办公室导航属性存在错误。一些故意重命名以澄清 也许这就是......
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace one2one
{
class Program
{
static void Main(string[] args)
{
var context = new Demo();
var instructor = new Instructor();
instructor.FirstName = "Big";
instructor.LastName = "Willi";
context.Set<Instructor>().Add(instructor);
var office = new OfficeAssignment();
office.Location = "is this where the demo broke down ? See POCO ";
office.InstructorUsingThisOffice = instructor;
context.Set<OfficeAssignment>().Add(office);
context.SaveChanges();
}
}
public class OfficeAssignment
{
// Specifying InstructorID as a primary
public Int32 InstructorID { get; set; }
public string Location { get; set; }
// Navigation property
public virtual Instructor InstructorUsingThisOffice { get; set; }
}
public class Instructor
{
// Primary key
public int InstructorID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
//navigation
//missing
public virtual OfficeAssignment TheofficeToUse { get; set; }
}
public class Demo : DbContext
{
DbSet<OfficeAssignment> officeAssignments { get; set; }
DbSet<Instructor> Instructors { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Configure the primary key for the OfficeAssignment
modelBuilder.Entity<OfficeAssignment>()
.HasKey(t => t.InstructorID);
modelBuilder.Entity<Instructor>()
.HasRequired(t => t.TheofficeToUse)
.WithRequiredPrincipal(d => d.InstructorUsingThisOffice); //current entity is principal, the navigation back.
// and we share the same key... MUST with EF 1:1 foreign key
}
}
}