这里使用SQLite数据库:
nuget: linq2db.SQLite
新建两个类:
Product
using System;
using LinqToDB;
using LinqToDB.Mapping;
[Table(Name = "Products")]
public class Product
{
[PrimaryKey]
public string ProductID { get; set; }
[Column(Name = "ProductName"), NotNull]
public string Name { get; set; }
[Column(Name = "Country")]
public string Country { get; set; }
}
public class DbNorthwind : LinqToDB.Data.DataConnection
{
public DbNorthwind() : base("Northwind") { }
public ITable<Product> Products => GetTable<Product>();
}
Merchandise
using LinqToDB.Mapping;
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp26
{
[Table(Name = "Merchandises")]
public class Merchandise
{
[PrimaryKey]
public string Id { get; set; }
[Column(Name = "Name")]
public string Name { get; set; }
}
}
运行:Program
using LinqToDB;
using LinqToDB.Configuration;
using LinqToDB.Data;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp26
{
class Program
{
static void Main(string[] args)
{
DataConnection.DefaultSettings = new MySettings();
using (var db = new DbNorthwind())
{
db.BeginTransaction();
db.Insert(new Merchandise { Id = Guid.NewGuid().ToString(), Name = "M" });
db.CommitTransaction();
}
using (var db = new DbNorthwind())
{
db.BeginTransaction();
var product = new Product { Name = "CF", ProductID = Guid.NewGuid().ToString(), Country = "AM" };
db.Insert(product);
db.CommitTransaction();
}
using (var db = new DbNorthwind())
{
var query = from p in db.Products
orderby p.Name descending
select p;
foreach (var item in query)
{
Console.WriteLine(item.Name);
}
}
Console.WriteLine("Hello World!");
Console.ReadKey();
}
}
public class ConnectionStringSettings : IConnectionStringSettings
{
public string ConnectionString { get; set; }
public string Name { get; set; }
public string ProviderName { get; set; }
public bool IsGlobal => false;
}
public class MySettings : ILinqToDBSettings
{
public IEnumerable<IDataProviderSettings> DataProviders => Enumerable.Empty<IDataProviderSettings>();
public string DefaultConfiguration => "SQLite.Classic";
public string DefaultDataProvider => "SQLite.Classic";
public IEnumerable<IConnectionStringSettings> ConnectionStrings
{
get
{
yield return
new ConnectionStringSettings
{
Name = "Northwind",
ProviderName = "SQLite.Classic",
ConnectionString = @"Data Source=D:/ProgramData/test.db"
};
}
}
}
}