EF中新建表和关联表的方法

以机场表为例

private static AIRPORT_HELIPORTManager AirportHeliportManager => ManagerFactory.Instance.AIRPORT_HELIPORTManager; //机场主表管理类,可看作机场表或机场list集合

1、高度集成方法

string airp_uuid = Guid.NewGuid().ToString();

//集合中插入一条机场对象(对应表中插入一条记录)
AirportHeliportManager.Add(new AIRPORT_HELIPORT()
{

//依次对AIRPORT_HELIPORT属性赋值,包括关联表属性
    AIRPORT_HELIPORT_UUID = airp_uuid,

//关联子表对象AIRPORT_HELIPORT_TS直接赋值
    AIRPORT_HELIPORT_TS = new List<AIRPORT_HELIPORT_TS>() //该子表属性也是一个List集合
    {

  //子表集合中每条记录
        new AIRPORT_HELIPORT_TS()
        {
            AIRPORT_HELIPORT_UUID = airp_uuid,
            TIME_SLICE_ID = Guid.NewGuid().ToString(),

   //下级子表属性

   //这里的city不是List,因为一个机场时间片只对应一个city对象,而不像上面的机场对应多条机场时间片,所以机场时间片是list
            CITY = new CITY()
            {
                CITY_ID = Guid.NewGuid().ToString()
            }
        }
    }
});

2、分散赋值方法

上面的集中赋值方法逻辑紧凑,但理解费时,下面的分散赋值更便于理解

AIRPORT_HELIPORT ap = new AIRPORT_HELIPORT();

ap.AIRPORT_HELIPORT_UUID = "123";

AIRPORT_HELIPORT_TS apts = new AIRPORT_HELIPORT_TS()
{
    AIRPORT_HELIPORT_UUID = "",
    CITY = new CITY() { CITY_ID = "" }
};
ap.AIRPORT_HELIPORT_TS.Add(apts);

AirportHeliportManager.Add(ap);

原文地址:https://www.cnblogs.com/mol1995/p/7517484.html