星期四, 2月 21, 2019

[EF] 資料載入

練習一下要符合 Master-Detail 架構下,移動 Master 資料時,要帶出 Detail 相關資料,會同時使用到 Eager Loading 和 Lazy Loading

C# Code
using System.Data.Entity;

namespace WinFormsWithLoading
{
    public partial class Form1 : Form
    {
        EFDemoEntities _context;
        public Form1()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            _context = new EFDemoEntities();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _context.Order.Include(o => o.Customer).Load();
            // SQL Profile 就會側錄到下面的 TSQL 語法
            //SELECT
            //    [Extent1].[OrderID] AS[OrderID], 
            //    [Extent1].[OrderDate] AS[OrderDate], 
            //    [Extent1].[CustID] AS[CustID], 
            //    [Extent2].[CustID] AS[CustID1], 
            //    [Extent2].[CustName]
            //        AS[CustName]
            //FROM[dbo].[Order]
            //        AS[Extent1]
            //INNER JOIN[dbo].[Customer] AS[Extent2] ON[Extent1].[CustID] = [Extent2].[CustID]

            bsOrder.DataSource = _context.Order.Local.ToBindingList();
            bsOrder.PositionChanged += BsOrder_PositionChanged;
            bsOrder.MoveLast();

            txtOrderID.DataBindings.Add("Text", bsOrder, "OrderID");
            txtOrderDate.DataBindings.Add("Text", bsOrder, "OrderDate");
            txtCustID.DataBindings.Add("Text", bsOrder, "CustID");
            txtCustName.DataBindings.Add("Text", bsOrder, "Customer.CustName");

            bindingNavigator1.BindingSource = bsOrder;

        }

        private void BsOrder_PositionChanged(object sender, EventArgs e)
        {
            if (bsOrder.Current == null) return;
            Order order = (bsOrder.Current as Order);

            // 清除現有 Local Entity
            _context.OrderDetail.Local.ToList().ForEach(x => _context.Entry(x).State = EntityState.Deleted);

            // MSDN 文章寫法
            _context.Entry(order).Collection(o => o.OrderDetail).Load();

            // VFP 慣例寫法
            //_context.OrderDetail.Where(w => w.OrderID == order.OrderID).Load();

            dataGridView1.DataSource = null;
            dataGridView1.DataSource = _context.OrderDetail.Local.ToBindingList();

        }
    }
}

沒有留言:

張貼留言