WPF MVVM ObservableCollection / DataGrid多个Sql表

时间:2017-11-30 04:31:45

标签: c# mysql wpf mvvm datagrid

好的......我继续教我自己的方式......这是我最新的问题。哈!我有一个使用MVVM的WPF应用程序和三个不同的示例MySQL表,如下所示:

BOOKINGS

Booking_ID_Num | Book_Type_Num | Fac_ID_Num |
---------------|---------------|------------|
       1       |       1       |     2      |
       2       |       2       |     3      |
       3       |       1       |     1      |

BOOKING_TYPES

Book_Type_Num |  Book_Type |
--------------|------------|
      1       |  Full Time |
      2       | Singe Case |

设施

Fac_ID_Num | Facility_Name |
-----------|---------------|
    1      |   Joe's Shop  |
    2      |    MedRX      |
    3      | Grocery Story |

我将尝试尽可能简洁地解释这一点,随意批评......我想填充ObservableCollection并将ObservableCollection传递给DataGrid。我知道如何通过模型类填充ObservableCollection,但我不知道如何填充多个表。在这个例子中,我希望在ViewModel中有一个Observable Collection传递给DataGrid,其结构如下:

Booking_ID_Num | Book_Type_Num |  Book_Type  | Fac_ID_Num | Facility_Name |
---------------|---------------|-------------|------------|---------------|
       1       |       1       |  Full Time  |      2     |     MedRx     |
       2       |       2       | Single Case |      3     | Grocery Store |
       3       |       1       |  Full Time  |      1     |   Joe's Shop  |

基本上,我想在最终解决方案中使用Book_Type和Facility_Name,而无需在MySQL数据库中进行任何调整,例如创建新的“视图”等。那有意义吗?这个网站帮助我学习很棒。对这个模糊问题的任何帮助将不胜感激。非常感谢你!

1 个答案:

答案 0 :(得分:1)

创建单独的类,表示数据库中的数据和DataGrid上的数据。

例如:

public class Booking
{
    public int BookingIDNum { get; set; }
    public int BookTypeNum { get; set; }
    public int FacIDNum { get; set; }
}

public class BookingType
{
    public int BookTypeNum { get; set; }
    public string BookType { get; set; }
}

public class Facility
{
    public int FacIDNum { get; set; }
    public string FacilityName { get; set; }
}

public class ViewData
{
    public int BookingIDNum { get; set; }
    public int BookTypeNum { get; set; }
    public string BookType { get; set; }
    public int FacIDNum { get; set; }
    public string FacilityName { get; set; }

    public static ViewData From(Booking booking, BookingType bookingType, Facility facility)
    {
        return new ViewData
        {
            BookingIDNum = booking.BookingIDNum,
            BookingTypeNum = booking.BookingTypeNum,
            FacIDNum = booking.FacIDNum,
            BookType = bookingType.BookType,
            FacilityName = facility.FacilityName
        };
    }
}

在上面的示例中,类BookingBookingTypeFacility表示数据库中的数据,而ViewData将是您绑定在{{1}上的类}}