本 示例 使用SqlServer2005,先在 数据 库中创建一张表, 其中CustomerId是主键且自动增长;CustomerType用来保存int枚举,字段类型使用int;InsertTime将系统时间作为默认值 CREATE TABLE [ Customer ] ( [ CustomerId ] [ int ] IDENTITY ( 1 , 1 ) NOT NU
本示例使用SqlServer2005,先在数据库中创建一张表,
其中CustomerId是主键且自动增长;CustomerType用来保存int枚举,字段类型使用int;InsertTime将系统时间作为默认值
CREATE TABLE [Customer]( [CustomerId] [int] IDENTITY(1,1) NOT NULL, [CustomerName] [nvarchar](50) NOT NULL, [CustomerType] [int] NOT NULL, [Description] [int] NULL, [InsertTime] [datetime] NOT NULL default(getdate()), --用于测试在数据库中设置默认值 CONSTRAINT [PK_Customer] PRIMARY KEY([CustomerId]) ) ON [PRIMARY]
接下来创建相应的实体类,可以使用枚举:
public enum CustomerType
{
Home, Abroad
}
[Table]
public class Customer
{
[Column(IsPrimaryKey=true)]
[SqlServerColumn(IsIdentity=true)]//针对SqlServer特有的标识列
public int CustomerId { get; set; }
[Column]
public string CustomerName { get; set; }
[Column]
public CustomerType CustomerType { get; set; }
[Column]
public string Description { get; set; }
[Column]
[SqlServerColumn(GenerateInsert=AttributeBoolean.False)]//数据库中已有默认值,告诉Titan在生成Insert语句时不要包含本列
public DateTime InsertTime { get; set; }
}
使用Titan往数据库中添加一条记录:
class Program
{
static void Main(string[] args)
{
IDbSession se = OpenDbSession();
Customer customer = new Customer();
customer.CustomerName = "customer name";
customer.CustomerType = CustomerType.Abroad;
se.Insert(customer);
Console.WriteLine(string.Format("执行Insert后标识列返回的CustomerId={0}",customer.CustomerId));
se.Close();
Console.ReadLine();
}
static IDbSession OpenDbSession()
{
//使用SqlServer。如果是其它数据库则可以使用:OracleSqlProvider,MySqlSqlProvider,SQLiteSqlProvider...
Type providerType = typeof(SqlServerSqlProvider);
//数据库连接支付串
string connectionString = @"Data Source=192.168.17.129\SQLEXPRESS;Initial Catalog=titandemo;User Id=sa;Password=123456;";
//sql语句追踪,可以跟踪Titan生成的Sql语句,此处使用控制台中查看生成的Sql语句
ISqlTracer[] sqlTracers = new ISqlTracer[] { new ConsoleSqlTracer() };
return DbSessionFactory.CreateAndOpenSession(providerType, connectionString, sqlTracers);
}
}
查看数据库已经添加成功:
控制台程序运行截屏:
从中可以看到生成的Sql语句中不包含CustomerId列和InsertTime列,
由于CustomerId使用了[SqlServerColumn(IsIdentity=true)]标注,Titan在生成Insert语句时不会包含此列,默认情况下还会在Insert语句中包含set @4=SCOPE_Identity()用以取回数据库自动生成的值。
另外数据库中InsertTime列使用了默认值,并且实体类属性中使用了[SqlServerColumn(GenerateInsert=AttributeBoolean.False)]标注,因此生成的Sql语句中也不包含此列。
关于IsIdentity=true标注,如果在[Column]标注中强制不返回,那么Insert语句中set @4=SCOPE_Identity()语句不会被生成。代码如下(注意红色部分):
[Table]
public class Customer
{
[Column(IsPrimaryKey = true, ReturnAfterInsert = AttributeBoolean.False)]
[SqlServerColumn(IsIdentity = true)]//针对SqlServer特有的标识列
public int CustomerId { get; set; }
再运行程序,发现Insert语句中不再包含set @4=SCOPE_Identity(),CustomerId的值仍为0。
Copyright © 2019- baoaiwan.cn 版权所有 赣ICP备2024042794号-3
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务