我创建了2个表示数据库实体的类.
第一实体:
public enum FlightStatus { checkIn,gateClosed,arrived,departedAt,unknown,canceled,expectedAt,delayed,InFlight } public class Flight { [Key] public string FlightNumber { get; set; } public DateTime Arrival { get; set; } public DateTime Departure { get; set; } public string CityOfArrival { get; set; } public string CityOfDeparture { get; set; } public char Terminal { get; set; } public FlightStatus Status { get; set; } public int Gate { get; set; } public virtual ICollection<Passanger> PassengerList { get; set; } public double PriceForFirstClass { get; set; } public double PriceForBusiness { get; set; } public double PriceForEconom { get; set; } }
第二实体:
public enum Sex { M,F } public enum FlightClass { First,Business,Econom,} public enum TicketType { OneWay,TwoWay,} public class Passenger { [Key] public string Passport { get; set; } public string flightNumber { get; set; } [ForeignKey("flightNumber")] public virtual Flight flight { get; set; } public string FirstName { get; set; } public string SecondName { get; set; } public string Nationality { get; set; } public DateTime DateOfbirthday { get; set; } public Sex SexOfPassanger { get; set; } public FlightClass ClassForPassanger { get; set; } public TicketType TypeOfTicket { get; set; } }
然后我创建了一个DbContext:
class FlightsDatabase : DbContext { public DbSet<Flight> Flights { get; set; } public DbSet<Flight> FlightsArchive { get; set; } public DbSet<Passenger> Passengers { get; set; } }
当我尝试使用此代码时:
using (FlightsDatabase flights = new FlightsDatabase()) { foreach (Flight flight in flights.Flights) { if (Math.Abs((flight.Departure - DateTime.Now).Days) <= 1) { timeCame(flight,null); } if (flight.Departure < DateTime.Now) { flightsToClean.Add(flight); } } moveOldFlights(flightsToClean,null); }
我收到这个错误
Multiple object sets per type are not supported. The object sets ‘Flights’ and ‘FlightsArchive’ can both contain instances of type ‘Project_Airline_Info.Models.Flight’.
所以我的问题是如何在DbContext类中创建具有相同泛型类型的2个DBset.
解决方法
简短的回答是你不能这样做.考虑以下代码行:
var flight = context.Set<Flight>().Where(f => f.FlightNumber = "123");
它如何知道用于获取数据的集合?
可能最简单的解决方法是继承Flight类并将其用于其他DbSet:
public class ArchiveFlight : Flight { }
你的背景:
public class FlightsDatabase :DbContext { public DbSet<Flight> Flights { get; set; } public DbSet<ArchiveFlight> FlightsArchive { get; set; } public DbSet<Passanger> Passengers { get; set; } }
这样做的好处是,您现在可以向归档的航班添加属性,例如归档日期:
public class ArchiveFlight : Flight { public DateTime DateArchived { get; set; } }