[英]Entity Framework how to produce this SQL code with code first approach?
I have 2 tables that should look like this 我有2张桌子应该看起来像这样
flights
: flight_id, route_id,... flights
:flight_id,route_id,... routes
: 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: 我是Entity Framework的新手,无法弄清楚如何很好地编写模型类,我尝试过这种方式:
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
. 您需要包括Route
模型,以便将其引用到Flight
模型中。 As I can see that you are doing a 1:n relationship, you can do it like this: 正如我所看到的,您正在做1:n关系,您可以这样做:
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: 如果您想要1:1关系,可以删除List
,这样它看起来像这样:
public Route Routing {get; set;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.