简体   繁体   中英

Entity Framework Fluent API Relationship Syntax

Code from: http://msdn.microsoft.com/en-us/data/jj591620

Given these EF classes:

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; } 
} 

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; } 
}

And given this fluent API code example:

   // Configure the primary key for the OfficeAssignment 
modelBuilder.Entity<OfficeAssignment>() 
    .HasKey(t => t.InstructorID); 

// Map one-to-zero or one relationship 
modelBuilder.Entity<OfficeAssignment>() 
    .HasRequired(t => t.Instructor) 
    .WithOptional(t => t.OfficeAssignment); // Confused here

And knowing that WithOptional method has this definition in MSDN:

RequiredNavigationPropertyConfiguration<TEntityType, TTargetEntityType>.WithOptional Method (Expression<Func<TTargetEntityType, TEntityType>>)

How is that possible to have t => t.OfficeAssignment where t is of type Instructor , and does not have a property named OfficeAssignment ?

The article miss this property on Instructor class.

public class Instructor 
{ 
    public virtual OfficeAssignment OfficeAssignment { get; set; }
}

Or remove the lambda expression.

modelBuilder.Entity<OfficeAssignment>() 
    .HasRequired(t => t.Instructor) 
    .WithOptional();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM