复杂点的使用3


code first的使用,支持复杂类型

public enum PhoneType {

Home,

Work,

Mobile,

}

public enum AddressType {

Home,

Work,

Other,

}

public class Address {

public string Line1 { get; set; }

public string Line2 { get; set; }

public string ZipCode { get; set; }

public string State { get; set; }

public string City { get; set; }

public string Country { get; set; }

}

public class Customer {

public Customer() {

this.PhoneNumbers = new Dictionary<PhoneType, string>();

this.Addresses = new Dictionary<AddressType, Address>();

}

  1. [AutoIncrement] // 创建自增长主键
  2. public int Id { get; set; }
  3. public string FirstName { get; set; }
  4. public string LastName { get; set; }
  5. [Index(Unique = true)] // 创建索引
  6. public string Email { get; set; }
  7. public Dictionary<PhoneType, string> PhoneNumbers { get; set; } //Blobbed
  8. public Dictionary<AddressType, Address> Addresses { get; set; } //Blobbed
  9. public DateTime CreatedAt { get; set; }

}

public class Order {

  1. [AutoIncrement]
  2. public int Id { get; set; }
  3. [References(typeof(Customer))] //外键
  4. public int CustomerId { get; set; }
  5. [References(typeof(Employee))] //Creates Foreign Key
  6. public int EmployeeId { get; set; }
  7. public Address ShippingAddress { get; set; } //Blobbed (no Address table)
  8. public DateTime? OrderDate { get; set; }
  9. public DateTime? RequiredDate { get; set; }
  10. public DateTime? ShippedDate { get; set; }
  11. public int? ShipVia { get; set; }
  12. public decimal Freight { get; set; }
  13. public decimal Total { get; set; }

}

public class OrderDetail {

  1. [AutoIncrement]
  2. public int Id { get; set; }
  3. [References(typeof(Order))] //Creates Foreign Key
  4. public int OrderId { get; set; }
  5. public int ProductId { get; set; }
  6. public decimal UnitPrice { get; set; }
  7. public short Quantity { get; set; }
  8. public decimal Discount { get; set; }

}

public class Employee {

public int Id { get; set; }

public string Name { get; set; }

}

public class Product {

public int Id { get; set; }

public string Name { get; set; }

public decimal UnitPrice { get; set; }

}

//Setup SQL Server Connection Factory

var dbFactory = new OrmLiteConnectionFactory(

@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\Database1.mdf;Integrated Security=True;User Instance=True",

SqlServerDialect.Provider);

//Use in-memory Sqlite DB instead

//var dbFactory = new OrmLiteConnectionFactory(

// ":memory:", false, SqliteDialect.Provider);

//Non-intrusive: All extension methods hang off System.Data.* interfaces

using (IDbConnection db = Config.OpenDbConnection())

{

//Re-Create all table schemas:

db.DropTable();

db.DropTable();

db.DropTable();

db.DropTable();

db.DropTable();

db.CreateTable();

db.CreateTable();

db.CreateTable();

db.CreateTable();

db.CreateTable();

db.Insert(new Employee { Id = 1, Name = "Employee 1" });

db.Insert(new Employee { Id = 2, Name = "Employee 2" });

var product1 = new Product { Id = 1, Name = "Product 1", UnitPrice = 10 };

var product2 = new Product { Id = 2, Name = "Product 2", UnitPrice = 20 };

db.Save(product1, product2);

var customer = new Customer {

FirstName = "Orm",

LastName = "Lite",

Email = "ormlite@servicestack.net",

PhoneNumbers =

{

{ PhoneType.Home, "555-1234" },

{ PhoneType.Work, "1-800-1234" },

{ PhoneType.Mobile, "818-123-4567" },

},

Addresses =

{

{ AddressType.Work, new Address {

Line1 = "1 Street", Country = "US", State = "NY", City = "New York", ZipCode = "10101" }

},

},

CreatedAt = DateTime.UtcNow,

};

var customerId = db.Insert(customer, selectIdentity: true); //Get Auto Inserted Id

customer = db.Single(new { customer.Email }); //Query

Assert.That(customer.Id, Is.EqualTo(customerId));

//Direct access to System.Data.Transactions:

using (IDbTransaction trans = db.OpenTransaction(IsolationLevel.ReadCommitted))

{

var order = new Order {

CustomerId = customer.Id,

EmployeeId = 1,

OrderDate = DateTime.UtcNow,

Freight = 10.50m,

ShippingAddress = new Address {

Line1 = "3 Street", Country = "US", State = "NY", City = "New York", ZipCode = "12121" },

};

db.Save(order); //Inserts 1st time

  1. //order.Id populated on Save().
  2. var orderDetails = new[] {
  3. new OrderDetail {
  4. OrderId = order.Id,
  5. ProductId = product1.Id,
  6. Quantity = 2,
  7. UnitPrice = product1.UnitPrice,
  8. },
  9. new OrderDetail {
  10. OrderId = order.Id,
  11. ProductId = product2.Id,
  12. Quantity = 2,
  13. UnitPrice = product2.UnitPrice,
  14. Discount = .15m,
  15. }
  16. };
  17. db.Save(orderDetails);
  18. order.Total = orderDetails.Sum(x => x.UnitPrice * x.Quantity * x.Discount) + order.Freight;
  19. db.Save(order); //Updates 2nd Time
  20. trans.Commit();

}

}

[Ignore] 可以忽略某个属性

![此处输入图片的描述][1]

[Alias("Shippers")]

public class Shipper

: IHasId

{

[AutoIncrement]

[Alias("ShipperID")]

public int Id { get; set; }

  1. [Required]//是否必须
  2. [Index(Unique = true)]//索引
  3. [StringLength(40)]//长度
  4. public string CompanyName { get; set; }
  5. [StringLength(24)]
  6. public string Phone { get; set; }
  7. [References(typeof(ShipperType))]
  8. public int ShipperTypeId { get; set; }

}

这个基本就够用了 codefirst啊

[Alias("ShipperTypes")]

public class ShipperType

: IHasId

{

[AutoIncrement]

[Alias("ShipperTypeID")]

public int Id { get; set; }

  1. [Required]
  2. [Index(Unique = true)]
  3. [StringLength(40)]
  4. public string Name { get; set; }

}

public class SubsetOfShipper

{

public int ShipperId { get; set; }

public string CompanyName { get; set; }

}

public class ShipperTypeCount

{

public int ShipperTypeId { get; set; }

public int Total { get; set; }

}

  1. [Alias("UserAuth")]//别名
  2. [CompositeIndex(true, "CompanyId", "UserName")]//复合索引
  3. public class MyCustomUserAuth
  4. {
  5. [AutoIncrement]
  6. public int Id { get; set; }
  7. [References(typeof(Company))]
  8. public int CompanyId { get; set; }
  9. public string UserName { get; set; }
  10. public string Email { get; set; }
  11. }

事务的支持

var trainsType = new ShipperType { Name = "Trains" };

var planesType = new ShipperType { Name = "Planes" };

//Playing with transactions

using (IDbTransaction dbTrans = db.OpenTransaction())

{

db.Save(trainsType);

db.Save(planesType);

  1. dbTrans.Commit();

}

using (IDbTransaction dbTrans = db.OpenTransaction(IsolationLevel.ReadCommitted))

{

db.Insert(new ShipperType { Name = "Automobiles" });

Assert.That(db.Select(), Has.Count.EqualTo(3));

}

Assert.That(db.Select(), Has.Count(2));

修改表名

  1. dbConn.GetDialectProvider().GetQuotedTableName(modelType.GetModelDefinition())// 获取表名(根据类获取表名)

//oldtableName 因为老表已经不存在了(即老表对应的那个类),所以只能老表名用字符串

public static void AlterTable(this IDbConnection dbConn, Type modelType, string command)

{

var person = db.SqlScalar("exec sp_name @OLDtablename, @newtablename", new { OLDtablename= "oldtableName", tablename= dbConn.GetDialectProvider().GetQuotedTableName(modelType.GetModelDefinition()) });

}

添加列

db.AddColumn(t => t.tim);

修改列名

db.ChangeColumnName(t => t.tim,"ss");

修改列

db.AlterColumn(t => t.tim);

删除列

db.DropColumn("columnName"); //Type LetterWeighting, string columnName

删除外键

db.DropForeignKey("ForeignKeyName"); //

添加外键

public enum OnFkOption

{

Cascade,

SetNull,

NoAction,

SetDefault,

Restrict

}

dbConnection.AddForeignKey<TypeWithNoForeignKeyInitially, ReferencedType>( t => t.RefId, tr => tr.Id, OnFkOption.NoAction, OnFkOption.Cascade, "FK_ADDED");

// 删除索引

db.DropIndex("IndexName"); //

//添加索引

db.CreateIndex(t => t.tim, "ss",false); // 字段,索引名 ,是否唯一索引

// 多列索引 源代码只支持在一个列上创建索引 可以加入新的扩展方法

在OrmLiteSchemaModifyApi.cs中 加入新方法

  1. public static void CreateIndex<T>(this IDbConnection dbConn, string fields,
  2. string indexName = null, bool unique = false)
  3. {
  4. var sourceMD = ModelDefinition<T>.Definition;
  5. string name = indexName.IsNullOrEmpty() ?
  6. (unique ? "uidx" : "idx") + "_" + sourceMD.ModelName + "_" + fields.Replace(",", "").Trim() :
  7. indexName;
  8. string command = string.Format("CREATE{0}INDEX {1} ON {2}({3});",
  9. unique ? " UNIQUE " : " ",
  10. name,
  11. sourceMD.ModelName,
  12. fields);
  13. dbConn.ExecuteSql(command);
  14. }

使用

为LetterWeighting的两个列创建非聚集索引

List listField = new List();

var sourceMD = ModelDefinition.Definition;

listField.Add(sourceMD.GetFieldDefinition(t => t.Weighting).FieldName);

listField.Add(sourceMD.GetFieldDefinition(t => t.tim).FieldName);

db.CreateIndex(string.Join(",", listField.ToArray()), "ss", false);

//建议 最好动手实践下. 如果没有你需要的codefirst代码(比如如果创建索引).建议通过先在数据库里设置好(创建索引),然后通过t4模板生成,看看是否有你需要的代码(创建索引的代码)

硬货随后奉上 group having怎能没有呢

ServiceStack.OrmLite 笔记9 -code first 必须的代码优先的更多相关文章

  1. ServiceStack.OrmLite 笔记2 -增

    ServiceStack.OrmLite 笔记2 这篇主要介绍 增加 db.Insert(new Employee { Id = 1, Name = "Employee 1" }) ...

  2. ServiceStack.OrmLite 笔记

    ServiceStack.OrmLite 笔记1 ServiceStack.OrmLite 这个东东就是个orm框架,可以实现类似ef的效果.具体的就不这里班门弄斧了. 支持 SqlServerDia ...

  3. ServiceStack.OrmLite 笔记8 -还是有用的姿势

    复杂点的使用2 InsertAll, UpdateAll and DeleteAll 的参数要是IEnumerables Each关键字 返回 IEnumerable 并且是延迟加载的 全局设置 当字 ...

  4. ServiceStack.OrmLite 笔记10-group having 分页orderby等

    group having 分页等 var ev = OrmLiteConfig.DialectProvider.SqlExpression(); group的使用 同sql一样,注意group分组的字 ...

  5. ServiceStack.OrmLite 笔记5 改

    修改 db.Update(new Person { Id = 1, FirstName = "Jimi", LastName = "Hendrix", Age ...

  6. ServiceStack.OrmLite 笔记4 删

    删除 db.DeleteAll(); //各种姿势 db.Delete(p => p.Age == 27);// db.Delete(q => q.Where(p => p.Age ...

  7. ServiceStack.OrmLite 学习笔记7-复杂点的使用1

    复杂点的使用1 先看看这2个类 class Customer { public int Id { get; set; } ... } class CustomerAddress { public in ...

  8. ServiceStack.OrmLite中的一些"陷阱"(2)

    注:此系列不是说ServiceStack.OrmLite的多个陷阱,这仅仅个人认为是某一个陷阱(毕竟我踩坑了)而引发的思考. 前文说到了项目需要使用两种不同的数据库语言,虽说前文问题已基本解决了,但是 ...

  9. ServiceStack.OrmLite中的一些"陷阱"(1)

    使用过ServiceStack.Ormlite的人都应该知道,其作为一个轻量级的ORM,使用的便捷度非常高,用起来就一个字:爽!而支撑其便捷度的,是库内大量地使用了扩展方法及静态变量. 首先先从源头入 ...

随机推荐

  1. 关于事件触发的一个小tips

    今天看到如下代码 window.globalEvent.bind('hotelHotTableRendered', function () { $('#hotelHotTd a').each(func ...

  2. 161020、web调试工具fiddler介绍及使用

    简介: Fiddler是一个http协议调试代理工具,它能够记录并检查所有你的电脑和互联网之间的http通讯,设置断点,查看所有的"进出"Fiddler的数据(指cookie,ht ...

  3. Linux计划任务,自动删除n天前的旧文件【转】

    转自:http://blog.csdn.net/jehoshaphat/article/details/51244237 转载地址:http://yaksayoo.blog.51cto.com/510 ...

  4. 转:redis常用命令

    一 Redis介绍 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从2010年3月15日起,Redis的开发 ...

  5. nginx完美支持yii2框架

    nginx完美支持yii2框架 server {listen 80;server_name www.peita.net peita.net;# default_server;access_log /d ...

  6. php socket通信(tcp/udp)

    注意 1.在socket_bind的时候ip地址不能真回环地址如127.0.0.1 2.server.php后台跑起来的时候 nohup php server.php > /var/tmp/a. ...

  7. python:配置文件configparser

    #-*- coding:utf8 -*- # Auth:fulimei import configparser #第一个标签 conf=configparser.ConfigParser() conf ...

  8. URL List

    wifi driver http://wenku.baidu.com/view/5fb275e9b8f67c1cfad6b85e.html http://wenku.baidu.com/view/a5 ...

  9. 20150612_Andriod contextual action mode 菜单

    参考地址:http://www.xuebuyuan.com/1114028.html              http://www.cnblogs.com/mengdd/p/3564782.html ...

  10. Python学习笔记-Day3-文件操作

    open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True) 打开文件并返回一个 ...