DataVeryLite入門教程(二) Entity篇


DataVeryLite 是基於.net 4.0的數據庫持久化ORM框架.
目前支持的數據庫有Sqlserver,Mysql,Oracle,Db2,PostgreSql,Sqlite和Access.
 
最好先閱讀DataVeryLite入門教程(一) 配置篇,然后再閱讀本篇。如果你覺得麻煩也可以跳過。
Entity是ORM中的核心對象之一,一個繼承Entity的對象對應於數據庫中的一個表。
Entity提供豐富的API對表中的單條數據進行操作。
比如根據id或其他條件,加載,刪除,插入,更新和部分字段更新等API。
 
 
1,為數據庫建一張表(本系列如無特殊說明都采用sqlserver數據庫,你可以根據自己的需要改成其他庫,相信不難辦到)
CREATE TABLE [dbo].[Person] (  [Id] int PRIMARY KEY IDENTITY(1,1) ,  [Name] varchar(20) NULL ,  [Sex] varchar(20) NULL ,  [Phone] varchar(20) NULL ,  [Email] varchar(20) NULL )

 

2,創建一個c#控制台項目
 
 
3,添加App.config配置文件,並添加配置
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="mydb" connectionString="Data Source=.;Initial Catalog=mydb;Integrated Security=True" providerName="sqlserver"/>
  </connectionStrings>
</configuration>

 

4,通過nuget添加DataVeryLite.dll到項目
 
 
5,建立Person類,並加上屬性配置
   [Table(Key = "mydb")] public class Person : DataVeryLite.Core.Entity { [Column(Name = "Id", IsPrimaryKey = true)] public int Id { get; set; } [Column(Name = "Name")] public string Name { get; set; } [Column(Name = "Sex")] public string Sex { get; set; } [Column(Name = "Phone")] public string Phone { get; set; } [Column(Name = "Email")] public string Email { get; set; } }

 

6,Person.Save()方法
代碼如下:
private static void Main(string[] args) { var person = new Person(); person.Name = "天大地大"; person.Email = "gg@qq.com"; person.Save(); }

 

執行結果:
 
 
7,Person.Update(),重點推薦部分字段更新
代碼如下:
 new Person {Id = 1, Name = "海闊天空"}.Update();

執行結果如下:

 
8,Person.Load()方法
代碼如下:
 var personById = new Person(); personById.Load(By.Id(1)); Console.WriteLine(personById.Name + ":" + personById.Email);

結果如下:

 
 
9,Perons.Count屬性
代碼如下:
 Console.WriteLine("記錄數:" + new Person().Count);

結果如下:

 
10,Person.Del()方法
代碼如下:
new Person(){Id = 1}.Del();

 

結果如下:
 
 

項目地址 http://dataverylite.codeplex.com/

NuGet

PM> Install-Package DataVeryLite

  

Example lite

using System;
public class HelloWorld
{
   public static void Main(params string[] args)
   {
       var p=Models.Xe.Person();
       p.Load(By.Id(1));
       p.Del();
       Console.WriteLine(p.Name+","+p.Age);
   }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM