Basic CRUD

In First application, it shows how to insert a new object to database:

    var u = new User {Name = "tom"};
    u.Save();

Now, let's continue this work to change this code to complete basic CRUD for database.
  • First, make sure the c:\Test\test.mdb has User table, and the table data is following:
Id Name
1 tom
2 tom
  • Open Program.cs and change it as following:
using System;
using Leafing.Data;
 
class Program
{
    static void Main(string[] args)
    {
        var u = User.FindById(1);
        Console.WriteLine(u);
        Console.ReadLine();
    }
}
  • Run this application, it will show:
{ Id = 1, Name = tom }
  • Edit the Program.cs as following:
using System;
using Leafing.Data;
 
class Program
{
    static void Main(string[] args)
    {
        var u = User.FindById(1);
        Console.WriteLine("Read Object:\n{0}", u);
        u.Name = "jerry";
        u.Save();
        var u1 = User.FindById(1);
        Console.WriteLine("Updated Object:\n{0}", u1);
        Console.ReadLine();
    }
}
  • Run this application, it will show:
Read Object:
{ Id = 1, Name = tom }
Updated Object:
{ Id = 1, Name = jerry }
  • Edit the Program.cs as following:
using System;
using Leafing.Data;
 
class Program
{
    static void Main(string[] args)
    {
        var u = User.FindById(2);
        Console.WriteLine("Read Object:\n{0}", u);
        u.Delete();
        var u1 = User.FindById(2);
        if (u1 == null)
        {
            Console.WriteLine("After delete, the object doesn't find.");
        }
        Console.ReadLine();
    }
}
  • Run this application, it will show:
Read Object:
{ Id = 2, Name = tom }
After delete, the object doesn't find.
  • Open the c:\Test\test.mdb file, confirm the User table is following:
Id Name
1 jerry
  • Ok, we just finished the basic CRUD, have fun!

Last edited Oct 4, 2014 at 3:46 AM by lifeng, version 12

Comments

lifeng Jan 21, 2014 at 2:27 AM 
异常信息很清楚啊。
从Model继承,必须有一个类型为bigint或int,且自增,或者guid的主键。缺省是bigint。

limingzhang Jan 20, 2014 at 8:08 AM 
我的数据库版本为:Microsoft SQL Server 2008 (SP3) - 10.0.5512.0 (X64) Aug 22 2012 19:25:47 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)

不知道为什么在执行User.FindById(id)时总报“The type of member [Id] is [System.Int64] but sql value of it is [System.Int32]”。

另外想问一下:DBEntry在使用时数据库的表是否必须有一个类型为int且自增的主键。