通过外键实体框架获取数据详细信息

时间:2017-05-29 10:13:13

标签: asp.net-mvc entity-framework

我有两张桌子:

车辆类型:

TYPEID   TYPENAME
1        CAR
2        TRUCK

车辆

VEHICLEID TYPEID VEHICLENO
1          1      XX-XX-XX-XXXX
2          2      XX-XX-XX-XXXX

当我使用Entity Framework获取所有车辆数据时,它会喜欢:

{
    VEHICLEID : 1,
    TYPE : { TYPEID : 1, TYPENAME : 'CAR' },
    VEHICLENO : XX-XX-XX-XXXX
}

注意:我使用的是ASP.NET MVC,导入数据库(.edmx)。请帮忙创建viewmodel和这种类型的输出。

2 个答案:

答案 0 :(得分:1)

请检查以下内容是否适合ViewModel

public class VehicleDetails
{
    public int VehicleID { get; set; }
    public VehicleType Type { get; set; }
    public string VehicleNo { get; set; }
}

public class VehicleType
{
    public int TypeID { get; set; }
    public string TypeName { get; set; }
}

答案 1 :(得分:0)

我有点慢,但要建立@Saket发布的内容:

<强>的ViewModels

public class VehicleViewModel{
    public int vehicleId { get; set; }
    public string VehicleNo { get; set; }
    public VehicleType vehicleType { get; set; }
}

public class VehicleType{
    public int TypeId { get; set; }
    public string TypeName { get; set; }
}

这可能不准确,因为我不知道您的数据库结构,但这将是填充viewModel的代码的良好起点:

public IList<VehicleViewModel> GetAllVehicles(){
    var results = new List<VehicleViewModel>();
    using(var db = new DbContext()){
        var rawDbData = db.Vehicles.Include("VehicleTypes").ToList();
        foreach(var rawData in rawDbData){
            results.add(new VehicleViewModel{
                vehicleId = rawData.VehicleId,
                VehicleNo = rawData.VehicleNo,
                vehicleType = new VehicleType{
                    TypeId = rawData.VehicleTypes.TypeId,
                    TypeName = rawData.VehicleTypes.TypeName
                }
            })
        }
    }
    return results;
}