1

我正在使用 Entity Framework 4.1,我想映射以下内容。

Car 
- Car_ID
- Name
- Created


Part
- Part_ID
- Car_ID
- Name
- Created

所以“汽车”可以有 0 个或更多部分。并且零件必须与汽车相关联。

public class Car
{
  [Key]
  [Column("Car_Id")]
   public int Id {get;set;}

   ..
   ..

   public ICollection<Parts> Parts { get; set; } 
}


public class Part
{
  [Key]
  [Column("Part_Id")]
   public int Id {get;set;}

   ..
   ..

   public Car Car { get; set; } 
}

我的上下文如下所示:

public class MyContext :  DbContext
{
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     modelBuilder.Configurations.Add(new CarConfiguration());
     modelBuilder.Configurations.Add(new PartConfiguration());
 }

}




public class CarConfiguration : EntityTypeConfiguration<Car>
{
      public DealerDemoEnrollmentConfiguration()
      {
          this.ToTable("Cars", SchemaName);
          this.HasKey(x => x.Id);
          this.HasMany(x => x.Parts);
      }
}

public class PartConfiguration : EntityTypeConfiguration<Part>
{
      public DealerDemoEnrollmentConfiguration()
      {
          this.ToTable("Parts", SchemaName);
          this.HasKey(x => x.Id);
          this.HasRequired(x => x.Car);
      }
}
  1. 我希望 Car 成为“主”实体,所以如果我想添加一个部分,我必须这样做:

    car.Add(部分);

  2. 默认情况下会延迟加载零件还是每次我加载汽车时都会加载所有零件?我希望它默认延迟加载,除非我明确想要所有部分。

  3. 出于学习目的,如果我不想要 #1 怎么办,即我只想能够做到:

    part.Car = car // 保存部分,即不保存部分

4

0 回答 0