【问题标题】:Entity Framework 6 0.1 to 0.1 relationship with fluent apiEntity Framework 6 0.1 到 0.1 与 fluent api 的关系
【发布时间】:2018-10-04 10:45:29
【问题描述】:

假设我想在实体框架 6 中为公司拼车建模:

  • 我有员工和汽车。
  • 员工可以有车也可以没有车。
  • 汽车可以属于员工,也可以不属于员工。

我知道如何在具有中间表的关系数据库中对此进行建模:

EmployeeCarAssociation
-EmployeeId
-CarId

EmpoyeeIdCarId 作为主键并在两列上使用唯一约束。

但是如何使用 EF6 Fluent Api 创建这种 0.1 到 0.1 的关系?

【问题讨论】:

    标签: c# entity-framework entity-framework-6 ef-fluent-api


    【解决方案1】:

    试试这个代码:

    public class Employee
    {
        public int Id { get; set; }
        public Car Car { get; set; }
        public int? CarId { get; set; }
    }
    
    public class Car
    {
        public int Id { get; set; }
        public Employee Employee { get; set; }
    }
    
    public class ApplicationDbContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Car> Cars { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Car>()
                .HasOptional(c => c.Employee)
                .WithOptionalDependent(e => e.Car)
                .Map(config =>
                {
                    config.MapKey("EmployeeId");
                });
    
            base.OnModelCreating(modelBuilder);
        }
    }
    

    【讨论】:

    • 这适用于实体框架,但不会在数据库级别强制执行 0.1-0.1 关系。它只在 Car-Table 中为 EmployeeId 创建一个 ForeignKey-Constraint。从技术上讲,如果将值直接输入数据库,则仍然可以将多辆汽车分配给一名员工。但只要只使用实体框架来改变数据,这就是要走的路。
    猜你喜欢
    • 1970-01-01
    • 2013-01-26
    • 2023-01-25
    • 2017-04-04
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    相关资源
    最近更新 更多