简体   繁体   中英

Can't cast base class object to derived type object, Entity Framework code-first

I understand that it is impossible in C#, but I need to do it somehow. I have two classes, a base class for list of flights.

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<Passenger> Passengers { get; set; }

        public double PriceForFirstClass { get; set; }
        public double PriceForBusiness { get; set; }
        public double PriceForEconom { get; set; }
}

And derived class for archive list of flights.

class ArchiveFlight :Flight
{
}

Here is my DbContext class.

 class FlightsDatabase : DbContext
 {
        protected override void OnModelCreating(DbModelBuilder builder)
        {
            builder.Entity<Flight>().HasMany(x => x.Passengers).
                WithOptional(x => x.Flight).HasForeignKey(x => x.flightNumber).WillCascadeOnDelete(true);
        }

        public DbSet<Flight> Flights { get; set;}
        public DbSet<ArchiveFlight> FlightsArchive { get; set; }
        public DbSet<Passenger> Passengers { get; set; }
    }
}

I need to do something like this.

flights.FlightsArchive.Add((ArchiveFlight)flightToclean);
flights.Flights.Remove(flightToclean);

Where flightToclean is type of Flight . flights is type of FlightsDatabase .

Can I do this shortly or do I need to create new ArchiveFlight object and copy all properties of Flight object to new ArchiveFlight object?

If I understood right, you have Flight entity in your context, and a FlightArchive entity, and once a flight is done, you want to move that flight in the FlightArchive collection.

To achive this, the best solution will be to get rid of FlightArchive entity, and to create property of type bool in Flight model.

In this way you can set that property to true, once a flight is done(old). It will be more easy for future data manipulation.

so, in your :

  public class Flight 
    {
          ...
     public bool FlightArchive {get;set;}
    }

then, when the flight is done, you can do this:

var flight=_context.Flights.Find(flightId);
flight.FlightArchive =true;

when you need the flight list: you can do:

var flightList=_context.Flights.Any(x=>!x.FlightArchive).ToList()

var flightArchive=_context.Flights.Any(x=>x.FlightArchive).ToList();

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