Yêu cầu mọi thông tin sao chép từ blog này phải được ghi rõ đầy đủ: Thông tin được sao chép từ "http://www.dangngochoangthanh.blogspot.com".

Cool wallpaper http://www.fancymessage.com

EMOJI KEYBOARD PRO http://emojiselector.com

THƯ VIỆN HÌNH ĐỘNG FLASH ANIMATION: http://flashanimationlibrary.blogspot.ru/

Hệ thống học trực tuyến đang được phát triển và sẽ đưa vào sử dụng vào cuối năm nay. Hãy xem qua một số demo của Học Trực Tuyến.


HỌC TRỰC TUYẾN ĐÃ CUNG CẤP PHIÊN BẢN TRUY CẬP QUA MOBILE http://dangngochoangthanh.blogspot.com/?m=1

XEM KÊNH HỌC TRỰC TUYẾN TRÊN YOUTUBE



Search on This Blog

Sunday, December 25, 2011

Làm việc với ADO.NET Entity


Bước 1. Tạo một dự án trong Visual Studio: có thể là dự án ASP.NET hoặc WinForm.
Bước 2. Kích chuột phải vào dự án và chọn Add > New Items > ADO.NET Entity Data Model

Bước 3. Đặt tên và Nhấp Next



Bước 4. Chọn Generate from Database > Next.

Bước 5. Tạo một kết nối bằng cách nhấp vào New Connection và cấu hình:

Server name: server lưu trữ dữ liệu. Ví dụ: chọn localhost
Use SQL Server Authentication: login vào dữ liệu bằng tài khoản được cấp. Ví dụ: username=sa; password=123.
Select or Enter a Database name: nhập tên database cần làm việc.
Sau đó, nhấp Test Connection để kiểm tra. Nếu thông báo:

Thì đã thành công. Chuyển sang bước tiếp theo.
Bước 6. Chọn các bảng dữ liệu trong Database

Bước 7. Nhấp Finish. Khi đó, các thực thể sẽ được khởi tạo. Ví dụ, trong trường hợp này, tôi có các thực thể: DoAnVBEntities. Mã sau đây do VS sinh tự động:

//------------------------------------------------------------------------------ 
  //  <auto-generated> 
  //    This code was generated from a template. 
  // 
  //    Manual changes to this file may cause  unexpected behavior in your application. 
  //    Manual changes to this file will be  overwritten if the code is regenerated. 
  //  </auto-generated> 
  //------------------------------------------------------------------------------ using System;
  using System.Data.Objects;
  using System.Data.Objects.DataClasses;
  using System.Data.EntityClient;
  using System.ComponentModel;
  using System.Xml.Serialization;
  using System.Runtime.Serialization;

[assembly: EdmSchemaAttribute()]

namespace EntityModel
  {
  #region Contexts
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  public partial class DoAnVBEntities : ObjectContext
  {
  #region Constructors
  
  /// <summary>
  /// Initializes a new DoAnVBEntities object using the  connection string found in the 'DoAnVBEntities' section of the application  configuration file.
  /// </summary>
  public  DoAnVBEntities() : base("name=DoAnVBEntities", "DoAnVBEntities")
  {
  this.ContextOptions.LazyLoadingEnabled  = true;
  OnContextCreated();
  }
  
  /// <summary>
  /// Initialize a new DoAnVBEntities object.
  /// </summary>
  public  DoAnVBEntities(string connectionString) : base(connectionString, "DoAnVBEntities")
  {
  this.ContextOptions.LazyLoadingEnabled  = true;
  OnContextCreated();
  }
  
  /// <summary>
  /// Initialize a new DoAnVBEntities object.
  /// </summary>
  public  DoAnVBEntities(EntityConnection connection)  : base(connection, "DoAnVBEntities")
  {
  this.ContextOptions.LazyLoadingEnabled  = true;
  OnContextCreated();
  }
  
  #endregion 
  
  #region Partial Methods
  
  partial  void OnContextCreated();
  
  #endregion 
  
  #region ObjectSet Properties
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  public ObjectSet<tbl_Khoa>  tbl_Khoa
  {
  get
  {
  if  ((_tbl_Khoa == null))
  {
  _tbl_Khoa = base.CreateObjectSet<tbl_Khoa>("tbl_Khoa");
  }
  return  _tbl_Khoa;
  }
  }
  private  ObjectSet<tbl_Khoa>  _tbl_Khoa;
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  public ObjectSet<tbl_lop>  tbl_lop
  {
  get
  {
  if  ((_tbl_lop == null))
  {
  _tbl_lop = base.CreateObjectSet<tbl_lop>("tbl_lop");
  }
  return  _tbl_lop;
  }
  }
  private  ObjectSet<tbl_lop>  _tbl_lop;

       #endregion 
  #region AddTo  Methods
  
  /// <summary>
  /// Deprecated Method for adding a new object to the tbl_Khoa  EntitySet. Consider using the .Add method of the associated  ObjectSet&lt;T&gt; property instead.
  /// </summary>
  public void AddTotbl_Khoa(tbl_Khoa  tbl_Khoa)
  {
  base.AddObject("tbl_Khoa", tbl_Khoa);
  }
  
  /// <summary>
  /// Deprecated Method for adding a new object to the tbl_lop  EntitySet. Consider using the .Add method of the associated  ObjectSet&lt;T&gt; property instead.
  /// </summary>
  public void AddTotbl_lop(tbl_lop  tbl_lop)
  {
  base.AddObject("tbl_lop", tbl_lop);
  }

       #endregion 
  }

   #endregion 
  
  #region Entities
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  [EdmEntityTypeAttribute(NamespaceName="DoAnVBModel", Name="tbl_Khoa")]
  [Serializable()]
  [DataContractAttribute(IsReference=true)]
  public partial class tbl_Khoa : EntityObject
  {
  #region Factory Method
  
  /// <summary>
  /// Create a new tbl_Khoa object.
  /// </summary>
  /// <param  name="idKhoa">Initial value of  the idKhoa property.</param>
  /// <param  name="tenKhoa">Initial value of  the TenKhoa property.</param>
  public static tbl_Khoa  Createtbl_Khoa(global::System.Int32 idKhoa, global::System.String tenKhoa)
  {
  tbl_Khoa  tbl_Khoa = new tbl_Khoa();
  tbl_Khoa.idKhoa = idKhoa;
  tbl_Khoa.TenKhoa = tenKhoa;
  return  tbl_Khoa;
  }

       #endregion 
  #region Primitive Properties
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
  [DataMemberAttribute()]
  public global::System.Int32  idKhoa
  {
  get
  {
  return  _idKhoa;
  }
  set
  {
  if  (_idKhoa != value)
  {
  OnidKhoaChanging(value);
  ReportPropertyChanging("idKhoa");
  _idKhoa = StructuralObject.SetValidValue(value);
  ReportPropertyChanged("idKhoa");
  OnidKhoaChanged();
  }
  }
  }
  private  global::System.Int32  _idKhoa;
  partial  void OnidKhoaChanging(global::System.Int32 value);
  partial  void OnidKhoaChanged();
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
  [DataMemberAttribute()]
  public global::System.String  TenKhoa
  {
  get
  {
  return  _TenKhoa;
  }
  set
  {
  OnTenKhoaChanging(value);
  ReportPropertyChanging("TenKhoa");
  _TenKhoa = StructuralObject.SetValidValue(value, false);
  ReportPropertyChanged("TenKhoa");
  OnTenKhoaChanged();
  }
  }
  private  global::System.String  _TenKhoa;
  partial  void OnTenKhoaChanging(global::System.String value);
  partial  void OnTenKhoaChanged();

       #endregion 
  
  }
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  [EdmEntityTypeAttribute(NamespaceName="DoAnVBModel", Name="tbl_lop")]
  [Serializable()]
  [DataContractAttribute(IsReference=true)]
  public partial class tbl_lop : EntityObject
  {
  #region Factory Method
  
  /// <summary>
  /// Create a new tbl_lop object.
  /// </summary>
  /// <param  name="malop">Initial value of the  malop property.</param>
  /// <param  name="makhoa">Initial value of  the makhoa property.</param>
  public static tbl_lop  Createtbl_lop(global::System.Int32 malop, global::System.Int32 makhoa)
  {
  tbl_lop  tbl_lop = new tbl_lop();
  tbl_lop.malop = malop;
  tbl_lop.makhoa = makhoa;
  return  tbl_lop;
  }

       #endregion 
  #region Primitive Properties
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
  [DataMemberAttribute()]
  public global::System.Int32  malop
  {
  get
  {
  return  _malop;
  }
  set
  {
  if  (_malop != value)
  {
  OnmalopChanging(value);
  ReportPropertyChanging("malop");
  _malop = StructuralObject.SetValidValue(value);
  ReportPropertyChanged("malop");
  OnmalopChanged();
  }
  }
  }
  private  global::System.Int32  _malop;
  partial  void OnmalopChanging(global::System.Int32 value);
  partial  void OnmalopChanged();
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
  [DataMemberAttribute()]
  public global::System.Int32  makhoa
  {
  get
  {
  return  _makhoa;
  }
  set
  {
  if  (_makhoa != value)
  {
  OnmakhoaChanging(value);
  ReportPropertyChanging("makhoa");
  _makhoa = StructuralObject.SetValidValue(value);
  ReportPropertyChanged("makhoa");
  OnmakhoaChanged();
  }
  }
  }
  private  global::System.Int32  _makhoa;
  partial  void OnmakhoaChanging(global::System.Int32 value);
  partial  void OnmakhoaChanged();
  
  /// <summary>
  /// No Metadata Documentation available.
  /// </summary>
  [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
  [DataMemberAttribute()]
  public global::System.String  tenlop
  {
  get
  {
  return  _tenlop;
  }
  set
  {
  OntenlopChanging(value);
  ReportPropertyChanging("tenlop");
  _tenlop = StructuralObject.SetValidValue(value, true);
  ReportPropertyChanged("tenlop");
  OntenlopChanged();
  }
  }
  private  global::System.String  _tenlop;
  partial  void OntenlopChanging(global::System.String value);
  partial  void OntenlopChanged();

       #endregion 
  
  }

   #endregion 
  
  }
Bước 8. Thiết kế một Form như sau:
Trong đó:
                ListBox có tên là lbKhoa;
                ComboBox có tên là cbKhoa;
                Hai TextBox có tên là: txtTenKhoaMoi và txtKhoa;
                Các nút “Xem Khoa”, “Đổi Tên”, “Xóa” và “Thêm Khoa” lần lượt có tên là btXemKhoa, btUpdate, btXoa, btThem.
Bước 9. Ta thực thi các truy vấn tương ứng với Select, Update, Insert và Delete.
Phương thức
Giải thích
Select
Tạo một đối tượng DoAnVBEntities, sau đó sử dụng thuộc tính tbl_Khoa
Insert
Tạo một đối tượng DoAnVBEntities, sau đó sử dụng phương thức AddTotbl_Khoa.
Tham số trong trường hợp này là một thực thể Khoa, do đó, ta sử dụng phương thưc tĩnh Createtbl_Khoa của đối tượng tbl_Khoa.
Kết thúc việc thêm dữ liệu, ta triệu gọi phương thức SaveChanges.
Update và Delete
Ta làm hoàn toàn tương tự, nhưng lưu ý để chọn được đối tượng cần update hay delete, ta cần sử dụng LINQ để xử lý.
Đây là mã nguôn của chương trình minh họa:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EntityModel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //Liệt kê đối tượng select
        private void btShow_Click(object sender, EventArgs e)
        {
            DoAnVBEntities vb = new DoAnVBEntities();
            lbKhoa.DataSource = vb.tbl_Khoa;
            lbKhoa.DisplayMember = "TenKhoa";
        }
        //Thêm đối tượng Insert
        private void btThem_Click(object sender, EventArgs e)
        {
            DoAnVBEntities vb = new DoAnVBEntities();
            vb.AddTotbl_Khoa(tbl_Khoa.Createtbl_Khoa(0, txtKhoa.Text));
            vb.SaveChanges();
            Form1_Load(null, null);
            btShow_Click(null, null);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DoAnVBEntities vb = new DoAnVBEntities();
            cbKhoa.DataSource = vb.tbl_Khoa;
            cbKhoa.DisplayMember = "tenkhoa";
            btShow_Click(null, null);
        }

        //Update thông tin đối tượng
        private void btUpdate_Click(object sender, EventArgs e)
        {
            DoAnVBEntities vb = new DoAnVBEntities();
            var khoa = (from d in vb.tbl_Khoa
                        where d.TenKhoa == cbKhoa.Text
                        select d).First();
            khoa.TenKhoa = txtTenKhoaMoi.Text;
            vb.SaveChanges();
            Form1_Load(null, null);
        }

        //Xóa đối tượng
        private void btXoa_Click(object sender, EventArgs e)
        {
            DoAnVBEntities vb = new DoAnVBEntities();
            var khoa = (from d in vb.tbl_Khoa
                        where d.TenKhoa == cbKhoa.Text
                        select d).First();
            vb.DeleteObject(khoa);
            vb.SaveChanges();
            Form1_Load(null, null);
        }
    }
}
Chương trình khi thực thi:

No comments:

Post a Comment