I have 2 tables that should look like this
flights
: flight_id, route_id,... routes
: route_id,... I am new to Entity Framework and can't figure out how to write model classes so well, I have tried this way:
public class Flight
{
[Key]
public int flight_id { get; set; }
[ForeignKey("route_id")]
public int route_id { get; set; }
public int airline_id { get; set; }
public DateTime departure_time { get; set; }
public DateTime arrival_time { get; set; }
}
public class Route
{
[Key]
public int route_id { get; set; }
public int origin_city_id { get; set; }
public int destination_city_id { get; set; }
public DateTime departure_date { get; set; }
}
and I would like to get as a result
ALTER TABLE [dbo].[Flights]
ADD CONSTRAINT [FK_dbo.Flights_dbo.route_id]
FOREIGN KEY ([route_id]) REFERENCES [dbo].[Routes] ([route_id])
ON DELETE CASCADE;
You need to include the model Route
in order for you reference it to your model Flight
. As I can see that you are doing a 1:n relationship, you can do it like this:
public class Flight
{
[Key]
public int flight_id { get; set; }
[ForeignKey("route_id")]
public int route_id { get; set; }
public int airline_id { get; set; }
public DateTime departure_time { get; set; }
public DateTime arrival_time { get; set; }
public List<Route> Routes {get; set} //including the Route Model for
//you to properly reference it.
}
You can remove the List
if you want a 1:1 relationship so that it would look like this:
public Route Routing {get; set;}
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.