如何在实体框架中使用属性定义多对多 [英] How to define many to many with attributes in Entity Framework

查看:109
本文介绍了如何在实体框架中使用属性定义多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试对CarEmployee之间的多对多关系进行建模,其中保存了有关汽车使用时间的信息.因此,我需要一个介于两者之间的类,其中将包含这些其他属性.

I try to model many to many relationship between Car and Employee where the info about when the car was used are held. So I need a class inbetween which will hold those additional attributes.

SSCCE:

我有Person课:

  public class Person {
        public int Id { get; set}; 
  }

和从Person派生的类Employee:

public class Employee : Person {
      public virtual ICollection<EmployeeCar> EmployeeCar { get; set; }
}

和一个关联类EmployeeCar,其中包含属性dateFromdateTo:

and a association classEmployeeCar which holds attributes dateFrom, dateTo:

public class EmployeeCar {
    [Key, Column(Order = 0)]
    public virtual Car Car { get; set; } 
    [Key, Column(Order = 1)]
    public virtual Employee Employee { get; set; }

    public DateTime DateFrom{ get; set; }
    public DateTime DateTo { get; set; }
}  

最后是类Car:

public class Car {
        public int Id { get; set; }
        public virtual ICollection<EmployeeCar>  EmployeeCar { get; set; }
    }

我按住ApplicationDbContext中的

:

in ApplicationDbContext I hold:

    public DbSet<Person> Persons { get; set; }
    public DbSet<EmployeeCar> EmployeesCars { get; set; }
    public DbSet<Car> Cars { get; set; }

但是当我运行database-update时,我得到:

but when I run the database-update I get:

MyApp.EmployeeCar: : EntityType 'EmployeeCar' has no key defined. Define the key for this EntityType.
EmployeesCars: EntityType: EntitySet 'EmployeesCars' is based on type 'EmployeeCar' that has no keys defined.

如何解决这种情况?如何告诉实体框架CarEmployee的组合是关键?

How to fix that situation? How to tell Entity Framework that combination of Car and Employee is the key?

推荐答案

您需要将ID属性本身添加到模型定义中-EF可以自动添加外键属性,但是可能不喜欢将导航属性视为键.

You would need to add the ID properties themselves to the model definition -- EF can add foreign key properties automatically, but it probably doesn't like the idea of seeing navigation properties as keys.

public class EmployeeCar {
    [Key, Column(Order = 0)]
    public int CarId { get; set; }
    [Key, Column(Order = 1)]
    public int EmployeeId { get; set; }

    public virtual Car Car { get; set; }
    public virtual Employee Employee { get; set; }

    public DateTime DateFrom{ get; set; }
    public DateTime DateTo { get; set; }
}  

>首先创建代码,很多很多,关联表中还有其他字段

这篇关于如何在实体框架中使用属性定义多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆