天天看點

ServiceStack.OrmLite 筆記9 -code first 必須的代碼優先

複雜點的使用3

code first的使用,支援複雜類型

public enum PhoneType {

Home,

Work,

Mobile,

}

public enum AddressType {

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>();

[AutoIncrement] // 建立自增長主鍵
public int Id { get; set; }

public string FirstName { get; set; }
public string LastName { get; set; }

[Index(Unique = true)] // 建立索引
public string Email { get; set; }

public Dictionary<PhoneType, string> PhoneNumbers { get; set; }  //Blobbed
public Dictionary<AddressType, Address> Addresses { get; set; }  //Blobbed
public DateTime CreatedAt { get; set; }
           

public class Order {

[AutoIncrement]
public int Id { get; set; }

[References(typeof(Customer))]      //外鍵
public int CustomerId { get; set; }

[References(typeof(Employee))]      //Creates Foreign Key
public int EmployeeId { get; set; }

public Address ShippingAddress { get; set; } //Blobbed (no Address table)

public DateTime? OrderDate { get; set; }
public DateTime? RequiredDate { get; set; }
public DateTime? ShippedDate { get; set; }
public int? ShipVia { get; set; }
public decimal Freight { get; set; }
public decimal Total { get; set; }
           

public class OrderDetail {

[AutoIncrement]
public int Id { get; set; }

[References(typeof(Order))] //Creates Foreign Key
public int OrderId { get; set; }

public int ProductId { get; set; }
public decimal UnitPrice { get; set; }
public short Quantity { get; set; }
public decimal Discount { get; set; }
           

public class Employee {

public int Id { get; set; }

public string Name { get; set; }

public class Product {

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.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 = "[email protected]",

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

//order.Id populated on Save().

  var orderDetails = new[] {
      new OrderDetail {
          OrderId = order.Id,
          ProductId = product1.Id,
          Quantity = 2,
          UnitPrice = product1.UnitPrice,
      },
      new OrderDetail {
          OrderId = order.Id,
          ProductId = product2.Id,
          Quantity = 2,
          UnitPrice = product2.UnitPrice,
          Discount = .15m,
      }
  };

  db.Save(orderDetails);

  order.Total = orderDetails.Sum(x => x.UnitPrice * x.Quantity * x.Discount) + order.Freight;

  db.Save(order); //Updates 2nd Time

  trans.Commit();
           

[Ignore] 可以忽略某個屬性

![此處輸入圖檔的描述][1]

[Alias("Shippers")]

public class Shipper

: IHasId

[AutoIncrement]

[Alias("ShipperID")]

[Required]//是否必須
[Index(Unique = true)]//索引
[StringLength(40)]//長度
public string CompanyName { get; set; }

[StringLength(24)]
public string Phone { get; set; }

[References(typeof(ShipperType))]
public int ShipperTypeId { get; set; }
           

這個基本就夠用了 codefirst啊

[Alias("ShipperTypes")]

public class ShipperType

[Alias("ShipperTypeID")]

[Required]
[Index(Unique = true)]
[StringLength(40)]
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; }

[Alias("UserAuth")]//别名
[CompositeIndex(true, "CompanyId", "UserName")]//複合索引
public class MyCustomUserAuth
{
    [AutoIncrement]
    public int Id { get; set; }

    [References(typeof(Company))]
    public int CompanyId { get; set; }

    public string UserName { get; set; }

    public string Email { get; set; }
}
           

事務的支援

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);

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));

修改表名

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中 加入新方法

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

使用

為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怎能沒有呢

作者:

過錯

出處:http://www.cnblogs.com/wang2650/

關于作者:net開發做的久而已。十餘年時光虛度!

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接。如有問題,可以郵件:[email protected]

 聯系我,非常感謝。