From d4602e7cc72b2274cebcabc60608b7884e380df5 Mon Sep 17 00:00:00 2001 From: Rob Conery Date: Thu, 9 Jul 2009 13:43:59 -1000 Subject: [PATCH] Added AR test records to Generated folder in BugReports. Added test for IActiveRecord in Load which sets isnew and isfalse accordingly. Closes #32 --- SubSonic.Core/Extensions/Database.cs | 8 + SubSonic.Core/Schema/IActiveRecord.cs | 2 + SubSonic.Tests/BugReports/ActiveRecord.cs | 50 +- .../BugReports/AdvancedTemplates.cs | 75 - .../BugReports/Generated/ActiveRecord.cs | 7702 +++++++++++++++++ .../BugReports/Generated/ActiveRecord.tt | 599 ++ .../BugReports/Generated/Context.cs | 280 + .../BugReports/Generated/Context.tt | 277 + .../BugReports/Generated/SQLServer.ttinclude | 333 + .../BugReports/Generated/Settings.ttinclude | 548 ++ .../BugReports/Generated/StoredProcedures.cs | 55 + .../BugReports/Generated/StoredProcedures.tt | 30 + .../BugReports/Generated/Structs.cs | 1793 ++++ .../BugReports/Generated/Structs.tt | 60 + .../BugReports/LinqGeneratorBugs.cs | 47 + SubSonic.Tests/LINQ/BugReports.cs | 27 - SubSonic.Tests/SubSonic.Tests.csproj | 40 +- 17 files changed, 11817 insertions(+), 109 deletions(-) delete mode 100644 SubSonic.Tests/BugReports/AdvancedTemplates.cs create mode 100644 SubSonic.Tests/BugReports/Generated/ActiveRecord.cs create mode 100644 SubSonic.Tests/BugReports/Generated/ActiveRecord.tt create mode 100644 SubSonic.Tests/BugReports/Generated/Context.cs create mode 100644 SubSonic.Tests/BugReports/Generated/Context.tt create mode 100644 SubSonic.Tests/BugReports/Generated/SQLServer.ttinclude create mode 100644 SubSonic.Tests/BugReports/Generated/Settings.ttinclude create mode 100644 SubSonic.Tests/BugReports/Generated/StoredProcedures.cs create mode 100644 SubSonic.Tests/BugReports/Generated/StoredProcedures.tt create mode 100644 SubSonic.Tests/BugReports/Generated/Structs.cs create mode 100644 SubSonic.Tests/BugReports/Generated/Structs.tt create mode 100644 SubSonic.Tests/BugReports/LinqGeneratorBugs.cs delete mode 100644 SubSonic.Tests/LINQ/BugReports.cs diff --git a/SubSonic.Core/Extensions/Database.cs b/SubSonic.Core/Extensions/Database.cs index 14a457f..cc67b73 100644 --- a/SubSonic.Core/Extensions/Database.cs +++ b/SubSonic.Core/Extensions/Database.cs @@ -181,6 +181,14 @@ public static void Load(this IDataReader rdr, T item) currentField.SetValue(item, rdr.GetValue(i).ChangeTypeTo(valueType)); } } + + if (item is IActiveRecord) { + var arItem = (IActiveRecord)item; + arItem.SetIsLoaded(true); + arItem.SetIsNew(false); + + } + } /// diff --git a/SubSonic.Core/Schema/IActiveRecord.cs b/SubSonic.Core/Schema/IActiveRecord.cs index 05ba073..71fbccc 100644 --- a/SubSonic.Core/Schema/IActiveRecord.cs +++ b/SubSonic.Core/Schema/IActiveRecord.cs @@ -42,5 +42,7 @@ public interface IActiveRecord DbCommand GetDeleteCommand(); void SetKeyValue(object value); void SetIsLoaded(bool isLoaded); + void SetIsNew(bool isLoaded); + } } \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/ActiveRecord.cs b/SubSonic.Tests/BugReports/ActiveRecord.cs index 121f487..a9d2469 100644 --- a/SubSonic.Tests/BugReports/ActiveRecord.cs +++ b/SubSonic.Tests/BugReports/ActiveRecord.cs @@ -3,20 +3,58 @@ using System.Linq; using System.Text; using Xunit; +using SouthWind; namespace SubSonic.Tests.BugReports { + public class ActiveRecord { /// - /// Issue 58 on SubSonicThree site, reported by jonathan.channon (aka ZIPPY!~) - /// Reports a null return - cannot repro + /// Issue 32 - ActiveRecord - IsLoaded not set true when query is executed + /// http://github.com/subsonic/SubSonic-3.0/issues#issue/32 /// [Fact] - public void FindByPrimaryKey_Should_Not_Return_Null() { - var db = new Southwind.NorthwindDB(); - var table=db.FindByPrimaryKey("CategoryID"); - Assert.NotNull(table); + public void UsingLinq_With_ActiveRecord_Product_Should_Set_IsLoaded_True() { + var list = from p in Product.All() + where p.ProductID > 0 + select p; + + Assert.Equal(true, list.FirstOrDefault().IsLoaded()); + } + + + [Fact] + public void UsingLinq_With_ActiveRecord_Product_Should_Set_IsNew_False() { + var list = from p in Product.All() + where p.ProductID > 0 + select p; + + Assert.Equal(false, list.FirstOrDefault().IsNew()); + } + + [Fact] + public void CreatingNew_Product_Should_Set_IsNew_True() { + var product = new Product(); + Assert.Equal(true, product.IsNew()); + } + [Fact] + public void CreatingNew_Product_Should_Set_IsLoaded_False() { + var product = new Product(); + Assert.Equal(false, product.IsLoaded()); } + [Fact] + public void PullingSingle_Should_Set_New_Product_IsLoaded_True() { + var product = new Product(); + product = Product.SingleOrDefault(x => x.ProductID == 1); + Assert.Equal(true, product.IsLoaded()); + } + [Fact] + public void PullingSingle_Should_Set_New_Product_IsNew_False() { + var product = new Product(); + product = Product.SingleOrDefault(x => x.ProductID == 1); + Assert.Equal(false, product.IsNew()); + } } + } diff --git a/SubSonic.Tests/BugReports/AdvancedTemplates.cs b/SubSonic.Tests/BugReports/AdvancedTemplates.cs deleted file mode 100644 index 8d71348..0000000 --- a/SubSonic.Tests/BugReports/AdvancedTemplates.cs +++ /dev/null @@ -1,75 +0,0 @@ -// -// SubSonic - http://subsonicproject.com -// -// The contents of this file are subject to the New BSD -// License (the "License"); you may not use this file -// except in compliance with the License. You may obtain a copy of -// the License at http://www.opensource.org/licenses/bsd-license.php -// -// Software distributed under the License is distributed on an -// "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -// implied. See the License for the specific language governing -// rights and limitations under the License. -// -using System.Linq; -using WestWind; -using Xunit; - -namespace SubSonic.Tests.BugReports -{ - public class AdvancedTemplates - { - private readonly SubSonicDB _db; - - public AdvancedTemplates() - { - _db = new SubSonicDB(); - } - - /// - /// As reported by Christian Weyer in groups.google.com - /// http://groups.google.com/group/subsonicproject/browse_thread/thread/0009e205ad7b0130 - /// - [Fact] - public void LINQ_Query_Bug() - { - var results = from c in _db.Customers - from o in _db.Orders - from od in _db.OrderDetails - where c.CustomerID == o.CustomerID && o.OrderID == od.OrderID - select new - { - c.CustomerID, - c.CompanyName, - o.ShippedDate, - od.ProductID, - od.Quantity - }; - - Assert.Equal(500, results.Count()); - } - - /// - /// An other way to write the above query - /// - [Fact] - public void LINQ_Query_Bug_Take2() - { - var results = from c in _db.Customers - join o in _db.Orders on c.CustomerID equals o.CustomerID - join od in _db.OrderDetails on o.OrderID equals od.OrderID - select new - { - c.CustomerID, - c.CompanyName, - o.ShippedDate, - od.ProductID, - od.Quantity - }; - - Assert.Equal(500, results.Count()); - } - - - } -} \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/Generated/ActiveRecord.cs b/SubSonic.Tests/BugReports/Generated/ActiveRecord.cs new file mode 100644 index 0000000..0ddc64c --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/ActiveRecord.cs @@ -0,0 +1,7702 @@ + + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Data; +using SubSonic.DataProviders; +using SubSonic.Extensions; +using System.Linq.Expressions; +using SubSonic.Schema; +using System.Collections; +using SubSonic; +using SubSonic.Repository; +using System.ComponentModel; +using System.Data.Common; + +namespace SouthWind +{ + + + /// + /// A class which represents the Customers table in the Northwind Database. + /// + public partial class Customer: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Customer item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Customer(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Customer.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Customer(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Customer(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Customer.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Customer SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Customer single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Customer SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Customer single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "CustomerID"; + } + + public object KeyValue() + { + return this.CustomerID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.CustomerID.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Customer)){ + Customer compare=(Customer)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.CustomerID.ToString(); + } + + public string DescriptorColumn() { + return "CustomerID"; + } + public static string GetKeyColumn() + { + return "CustomerID"; + } + public static string GetDescriptorColumn() + { + return "CustomerID"; + } + + #region ' Foreign Keys ' + public IQueryable CustomerCustomerDemos + { + get + { + + var repo=SouthWind.CustomerCustomerDemo.GetRepo(); + return from items in repo.GetAll() + where items.CustomerID == _CustomerID + select items; + } + } + + public IQueryable Orders + { + get + { + + var repo=SouthWind.Order.GetRepo(); + return from items in repo.GetAll() + where items.CustomerID == _CustomerID + select items; + } + } + + #endregion + + + string _CustomerID; + public string CustomerID + { + get { return _CustomerID; } + set + { + if(_CustomerID!=value){ + _CustomerID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CustomerID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _CompanyName; + public string CompanyName + { + get { return _CompanyName; } + set + { + if(_CompanyName!=value){ + _CompanyName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CompanyName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ContactName; + public string ContactName + { + get { return _ContactName; } + set + { + if(_ContactName!=value){ + _ContactName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ContactName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ContactTitle; + public string ContactTitle + { + get { return _ContactTitle; } + set + { + if(_ContactTitle!=value){ + _ContactTitle=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ContactTitle"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Address; + public string Address + { + get { return _Address; } + set + { + if(_Address!=value){ + _Address=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Address"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _City; + public string City + { + get { return _City; } + set + { + if(_City!=value){ + _City=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="City"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Region; + public string Region + { + get { return _Region; } + set + { + if(_Region!=value){ + _Region=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Region"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _PostalCode; + public string PostalCode + { + get { return _PostalCode; } + set + { + if(_PostalCode!=value){ + _PostalCode=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="PostalCode"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Country; + public string Country + { + get { return _Country; } + set + { + if(_Country!=value){ + _Country=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Country"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Phone; + public string Phone + { + get { return _Phone; } + set + { + if(_Phone!=value){ + _Phone=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Phone"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Fax; + public string Fax + { + get { return _Fax; } + set + { + if(_Fax!=value){ + _Fax=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Fax"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Shippers table in the Northwind Database. + /// + public partial class Shipper: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Shipper item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Shipper(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Shipper.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Shipper(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Shipper(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Shipper.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Shipper SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Shipper single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Shipper SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Shipper single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "ShipperID"; + } + + public object KeyValue() + { + return this.ShipperID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.CompanyName.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Shipper)){ + Shipper compare=(Shipper)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.CompanyName.ToString(); + } + + public string DescriptorColumn() { + return "CompanyName"; + } + public static string GetKeyColumn() + { + return "ShipperID"; + } + public static string GetDescriptorColumn() + { + return "CompanyName"; + } + + #region ' Foreign Keys ' + public IQueryable Orders + { + get + { + + var repo=SouthWind.Order.GetRepo(); + return from items in repo.GetAll() + where items.ShipVia == _ShipperID + select items; + } + } + + #endregion + + + int _ShipperID; + public int ShipperID + { + get { return _ShipperID; } + set + { + if(_ShipperID!=value){ + _ShipperID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShipperID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _CompanyName; + public string CompanyName + { + get { return _CompanyName; } + set + { + if(_CompanyName!=value){ + _CompanyName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CompanyName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Phone; + public string Phone + { + get { return _Phone; } + set + { + if(_Phone!=value){ + _Phone=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Phone"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Suppliers table in the Northwind Database. + /// + public partial class Supplier: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Supplier item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Supplier(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Supplier.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Supplier(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Supplier(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Supplier.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Supplier SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Supplier single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Supplier SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Supplier single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "SupplierID"; + } + + public object KeyValue() + { + return this.SupplierID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.CompanyName.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Supplier)){ + Supplier compare=(Supplier)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.CompanyName.ToString(); + } + + public string DescriptorColumn() { + return "CompanyName"; + } + public static string GetKeyColumn() + { + return "SupplierID"; + } + public static string GetDescriptorColumn() + { + return "CompanyName"; + } + + #region ' Foreign Keys ' + public IQueryable Products + { + get + { + + var repo=SouthWind.Product.GetRepo(); + return from items in repo.GetAll() + where items.SupplierID == _SupplierID + select items; + } + } + + #endregion + + + int _SupplierID; + public int SupplierID + { + get { return _SupplierID; } + set + { + if(_SupplierID!=value){ + _SupplierID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SupplierID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _CompanyName; + public string CompanyName + { + get { return _CompanyName; } + set + { + if(_CompanyName!=value){ + _CompanyName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CompanyName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ContactName; + public string ContactName + { + get { return _ContactName; } + set + { + if(_ContactName!=value){ + _ContactName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ContactName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ContactTitle; + public string ContactTitle + { + get { return _ContactTitle; } + set + { + if(_ContactTitle!=value){ + _ContactTitle=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ContactTitle"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Address; + public string Address + { + get { return _Address; } + set + { + if(_Address!=value){ + _Address=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Address"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _City; + public string City + { + get { return _City; } + set + { + if(_City!=value){ + _City=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="City"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Region; + public string Region + { + get { return _Region; } + set + { + if(_Region!=value){ + _Region=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Region"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _PostalCode; + public string PostalCode + { + get { return _PostalCode; } + set + { + if(_PostalCode!=value){ + _PostalCode=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="PostalCode"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Country; + public string Country + { + get { return _Country; } + set + { + if(_Country!=value){ + _Country=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Country"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Phone; + public string Phone + { + get { return _Phone; } + set + { + if(_Phone!=value){ + _Phone=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Phone"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Fax; + public string Fax + { + get { return _Fax; } + set + { + if(_Fax!=value){ + _Fax=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Fax"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _HomePage; + public string HomePage + { + get { return _HomePage; } + set + { + if(_HomePage!=value){ + _HomePage=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="HomePage"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Order Details table in the Northwind Database. + /// + public partial class OrderDetail: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(OrderDetail item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public OrderDetail(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + OrderDetail.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public OrderDetail(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public OrderDetail(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + OrderDetail.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static OrderDetail SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + OrderDetail single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static OrderDetail SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + OrderDetail single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "OrderID"; + } + + public object KeyValue() + { + return this.OrderID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.ProductID.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(OrderDetail)){ + OrderDetail compare=(OrderDetail)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.ProductID.ToString(); + } + + public string DescriptorColumn() { + return "ProductID"; + } + public static string GetKeyColumn() + { + return "OrderID"; + } + public static string GetDescriptorColumn() + { + return "ProductID"; + } + + #region ' Foreign Keys ' + public IQueryable Orders + { + get + { + + var repo=SouthWind.Order.GetRepo(); + return from items in repo.GetAll() + where items.OrderID == _OrderID + select items; + } + } + + public IQueryable Products + { + get + { + + var repo=SouthWind.Product.GetRepo(); + return from items in repo.GetAll() + where items.ProductID == _ProductID + select items; + } + } + + #endregion + + + int _OrderID; + public int OrderID + { + get { return _OrderID; } + set + { + if(_OrderID!=value){ + _OrderID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OrderID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + int _ProductID; + public int ProductID + { + get { return _ProductID; } + set + { + if(_ProductID!=value){ + _ProductID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ProductID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + decimal _UnitPrice; + public decimal UnitPrice + { + get { return _UnitPrice; } + set + { + if(_UnitPrice!=value){ + _UnitPrice=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="UnitPrice"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + short _Quantity; + public short Quantity + { + get { return _Quantity; } + set + { + if(_Quantity!=value){ + _Quantity=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Quantity"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + decimal _Discount; + public decimal Discount + { + get { return _Discount; } + set + { + if(_Discount!=value){ + _Discount=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Discount"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the CustomerCustomerDemo table in the Northwind Database. + /// + public partial class CustomerCustomerDemo: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(CustomerCustomerDemo item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public CustomerCustomerDemo(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + CustomerCustomerDemo.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public CustomerCustomerDemo(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public CustomerCustomerDemo(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + CustomerCustomerDemo.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static CustomerCustomerDemo SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + CustomerCustomerDemo single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static CustomerCustomerDemo SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + CustomerCustomerDemo single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "CustomerID"; + } + + public object KeyValue() + { + return this.CustomerID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.CustomerID.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(CustomerCustomerDemo)){ + CustomerCustomerDemo compare=(CustomerCustomerDemo)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.CustomerID.ToString(); + } + + public string DescriptorColumn() { + return "CustomerID"; + } + public static string GetKeyColumn() + { + return "CustomerID"; + } + public static string GetDescriptorColumn() + { + return "CustomerID"; + } + + #region ' Foreign Keys ' + public IQueryable CustomerDemographics + { + get + { + + var repo=SouthWind.CustomerDemographic.GetRepo(); + return from items in repo.GetAll() + where items.CustomerTypeID == _CustomerTypeID + select items; + } + } + + public IQueryable Customers + { + get + { + + var repo=SouthWind.Customer.GetRepo(); + return from items in repo.GetAll() + where items.CustomerID == _CustomerID + select items; + } + } + + #endregion + + + string _CustomerID; + public string CustomerID + { + get { return _CustomerID; } + set + { + if(_CustomerID!=value){ + _CustomerID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CustomerID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _CustomerTypeID; + public string CustomerTypeID + { + get { return _CustomerTypeID; } + set + { + if(_CustomerTypeID!=value){ + _CustomerTypeID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CustomerTypeID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the CustomerDemographics table in the Northwind Database. + /// + public partial class CustomerDemographic: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(CustomerDemographic item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public CustomerDemographic(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + CustomerDemographic.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public CustomerDemographic(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public CustomerDemographic(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + CustomerDemographic.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static CustomerDemographic SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + CustomerDemographic single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static CustomerDemographic SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + CustomerDemographic single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "CustomerTypeID"; + } + + public object KeyValue() + { + return this.CustomerTypeID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.CustomerTypeID.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(CustomerDemographic)){ + CustomerDemographic compare=(CustomerDemographic)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.CustomerTypeID.ToString(); + } + + public string DescriptorColumn() { + return "CustomerTypeID"; + } + public static string GetKeyColumn() + { + return "CustomerTypeID"; + } + public static string GetDescriptorColumn() + { + return "CustomerTypeID"; + } + + #region ' Foreign Keys ' + public IQueryable CustomerCustomerDemos + { + get + { + + var repo=SouthWind.CustomerCustomerDemo.GetRepo(); + return from items in repo.GetAll() + where items.CustomerTypeID == _CustomerTypeID + select items; + } + } + + #endregion + + + string _CustomerTypeID; + public string CustomerTypeID + { + get { return _CustomerTypeID; } + set + { + if(_CustomerTypeID!=value){ + _CustomerTypeID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CustomerTypeID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _CustomerDesc; + public string CustomerDesc + { + get { return _CustomerDesc; } + set + { + if(_CustomerDesc!=value){ + _CustomerDesc=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CustomerDesc"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Region table in the Northwind Database. + /// + public partial class Region: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Region item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Region(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Region.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Region(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Region(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Region.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Region SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Region single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Region SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Region single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "RegionID"; + } + + public object KeyValue() + { + return this.RegionID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.RegionDescription.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Region)){ + Region compare=(Region)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.RegionDescription.ToString(); + } + + public string DescriptorColumn() { + return "RegionDescription"; + } + public static string GetKeyColumn() + { + return "RegionID"; + } + public static string GetDescriptorColumn() + { + return "RegionDescription"; + } + + #region ' Foreign Keys ' + public IQueryable Territories + { + get + { + + var repo=SouthWind.Territory.GetRepo(); + return from items in repo.GetAll() + where items.RegionID == _RegionID + select items; + } + } + + #endregion + + + int _RegionID; + public int RegionID + { + get { return _RegionID; } + set + { + if(_RegionID!=value){ + _RegionID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RegionID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _RegionDescription; + public string RegionDescription + { + get { return _RegionDescription; } + set + { + if(_RegionDescription!=value){ + _RegionDescription=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RegionDescription"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Territories table in the Northwind Database. + /// + public partial class Territory: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Territory item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Territory(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Territory.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Territory(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Territory(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Territory.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Territory SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Territory single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Territory SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Territory single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "TerritoryID"; + } + + public object KeyValue() + { + return this.TerritoryID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.TerritoryID.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Territory)){ + Territory compare=(Territory)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.TerritoryID.ToString(); + } + + public string DescriptorColumn() { + return "TerritoryID"; + } + public static string GetKeyColumn() + { + return "TerritoryID"; + } + public static string GetDescriptorColumn() + { + return "TerritoryID"; + } + + #region ' Foreign Keys ' + public IQueryable Regions + { + get + { + + var repo=SouthWind.Region.GetRepo(); + return from items in repo.GetAll() + where items.RegionID == _RegionID + select items; + } + } + + public IQueryable EmployeeTerritories + { + get + { + + var repo=SouthWind.EmployeeTerritory.GetRepo(); + return from items in repo.GetAll() + where items.TerritoryID == _TerritoryID + select items; + } + } + + #endregion + + + string _TerritoryID; + public string TerritoryID + { + get { return _TerritoryID; } + set + { + if(_TerritoryID!=value){ + _TerritoryID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="TerritoryID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _TerritoryDescription; + public string TerritoryDescription + { + get { return _TerritoryDescription; } + set + { + if(_TerritoryDescription!=value){ + _TerritoryDescription=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="TerritoryDescription"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + int _RegionID; + public int RegionID + { + get { return _RegionID; } + set + { + if(_RegionID!=value){ + _RegionID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RegionID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the EmployeeTerritories table in the Northwind Database. + /// + public partial class EmployeeTerritory: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(EmployeeTerritory item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public EmployeeTerritory(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + EmployeeTerritory.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public EmployeeTerritory(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public EmployeeTerritory(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + EmployeeTerritory.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static EmployeeTerritory SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + EmployeeTerritory single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static EmployeeTerritory SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + EmployeeTerritory single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "EmployeeID"; + } + + public object KeyValue() + { + return this.EmployeeID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.TerritoryID.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(EmployeeTerritory)){ + EmployeeTerritory compare=(EmployeeTerritory)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.TerritoryID.ToString(); + } + + public string DescriptorColumn() { + return "TerritoryID"; + } + public static string GetKeyColumn() + { + return "EmployeeID"; + } + public static string GetDescriptorColumn() + { + return "TerritoryID"; + } + + #region ' Foreign Keys ' + public IQueryable Employees + { + get + { + + var repo=SouthWind.Employee.GetRepo(); + return from items in repo.GetAll() + where items.EmployeeID == _EmployeeID + select items; + } + } + + public IQueryable Territories + { + get + { + + var repo=SouthWind.Territory.GetRepo(); + return from items in repo.GetAll() + where items.TerritoryID == _TerritoryID + select items; + } + } + + #endregion + + + int _EmployeeID; + public int EmployeeID + { + get { return _EmployeeID; } + set + { + if(_EmployeeID!=value){ + _EmployeeID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EmployeeID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _TerritoryID; + public string TerritoryID + { + get { return _TerritoryID; } + set + { + if(_TerritoryID!=value){ + _TerritoryID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="TerritoryID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Orders table in the Northwind Database. + /// + public partial class Order: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Order item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Order(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Order.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Order(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Order(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Order.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Order SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Order single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Order SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Order single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "OrderID"; + } + + public object KeyValue() + { + return this.OrderID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.CustomerID.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Order)){ + Order compare=(Order)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.CustomerID.ToString(); + } + + public string DescriptorColumn() { + return "CustomerID"; + } + public static string GetKeyColumn() + { + return "OrderID"; + } + public static string GetDescriptorColumn() + { + return "CustomerID"; + } + + #region ' Foreign Keys ' + public IQueryable Customers + { + get + { + + var repo=SouthWind.Customer.GetRepo(); + return from items in repo.GetAll() + where items.CustomerID == _CustomerID + select items; + } + } + + public IQueryable Employees + { + get + { + + var repo=SouthWind.Employee.GetRepo(); + return from items in repo.GetAll() + where items.EmployeeID == _EmployeeID + select items; + } + } + + public IQueryable OrderDetails + { + get + { + + var repo=SouthWind.OrderDetail.GetRepo(); + return from items in repo.GetAll() + where items.OrderID == _OrderID + select items; + } + } + + public IQueryable Shippers + { + get + { + + var repo=SouthWind.Shipper.GetRepo(); + return from items in repo.GetAll() + where items.ShipperID == _ShipVia + select items; + } + } + + #endregion + + + int _OrderID; + public int OrderID + { + get { return _OrderID; } + set + { + if(_OrderID!=value){ + _OrderID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OrderID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _CustomerID; + public string CustomerID + { + get { return _CustomerID; } + set + { + if(_CustomerID!=value){ + _CustomerID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CustomerID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + int _EmployeeID; + public int EmployeeID + { + get { return _EmployeeID; } + set + { + if(_EmployeeID!=value){ + _EmployeeID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EmployeeID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + DateTime _OrderDate; + public DateTime OrderDate + { + get { return _OrderDate; } + set + { + if(_OrderDate!=value){ + _OrderDate=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OrderDate"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + DateTime? _RequiredDate; + public DateTime? RequiredDate + { + get { return _RequiredDate; } + set + { + if(_RequiredDate!=value){ + _RequiredDate=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RequiredDate"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + DateTime? _ShippedDate; + public DateTime? ShippedDate + { + get { return _ShippedDate; } + set + { + if(_ShippedDate!=value){ + _ShippedDate=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShippedDate"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + int? _ShipVia; + public int? ShipVia + { + get { return _ShipVia; } + set + { + if(_ShipVia!=value){ + _ShipVia=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShipVia"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + decimal? _Freight; + public decimal? Freight + { + get { return _Freight; } + set + { + if(_Freight!=value){ + _Freight=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Freight"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ShipName; + public string ShipName + { + get { return _ShipName; } + set + { + if(_ShipName!=value){ + _ShipName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShipName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ShipAddress; + public string ShipAddress + { + get { return _ShipAddress; } + set + { + if(_ShipAddress!=value){ + _ShipAddress=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShipAddress"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ShipCity; + public string ShipCity + { + get { return _ShipCity; } + set + { + if(_ShipCity!=value){ + _ShipCity=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShipCity"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ShipRegion; + public string ShipRegion + { + get { return _ShipRegion; } + set + { + if(_ShipRegion!=value){ + _ShipRegion=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShipRegion"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ShipPostalCode; + public string ShipPostalCode + { + get { return _ShipPostalCode; } + set + { + if(_ShipPostalCode!=value){ + _ShipPostalCode=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShipPostalCode"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ShipCountry; + public string ShipCountry + { + get { return _ShipCountry; } + set + { + if(_ShipCountry!=value){ + _ShipCountry=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShipCountry"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the SubSonicTests table in the Northwind Database. + /// + public partial class SubSonicTest: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(SubSonicTest item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public SubSonicTest(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + SubSonicTest.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public SubSonicTest(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public SubSonicTest(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + SubSonicTest.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static SubSonicTest SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + SubSonicTest single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static SubSonicTest SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + SubSonicTest single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "SubSonicTestID"; + } + + public object KeyValue() + { + return this.SubSonicTestID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.Name.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(SubSonicTest)){ + SubSonicTest compare=(SubSonicTest)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.Name.ToString(); + } + + public string DescriptorColumn() { + return "Name"; + } + public static string GetKeyColumn() + { + return "SubSonicTestID"; + } + public static string GetDescriptorColumn() + { + return "Name"; + } + + #region ' Foreign Keys ' + #endregion + + + int _SubSonicTestID; + public int SubSonicTestID + { + get { return _SubSonicTestID; } + set + { + if(_SubSonicTestID!=value){ + _SubSonicTestID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SubSonicTestID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + int _Thinger; + public int Thinger + { + get { return _Thinger; } + set + { + if(_Thinger!=value){ + _Thinger=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Thinger"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Name; + public string Name + { + get { return _Name; } + set + { + if(_Name!=value){ + _Name=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _UserName; + public string UserName + { + get { return _UserName; } + set + { + if(_UserName!=value){ + _UserName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="UserName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + DateTime _CreatedOn; + public DateTime CreatedOn + { + get { return _CreatedOn; } + set + { + if(_CreatedOn!=value){ + _CreatedOn=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + decimal _Price; + public decimal Price + { + get { return _Price; } + set + { + if(_Price!=value){ + _Price=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Price"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + double _Discount; + public double Discount + { + get { return _Discount; } + set + { + if(_Discount!=value){ + _Discount=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Discount"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + decimal? _Lat; + public decimal? Lat + { + get { return _Lat; } + set + { + if(_Lat!=value){ + _Lat=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Lat"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + decimal? _Long; + public decimal? Long + { + get { return _Long; } + set + { + if(_Long!=value){ + _Long=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Long"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + bool _SomeFlag; + public bool SomeFlag + { + get { return _SomeFlag; } + set + { + if(_SomeFlag!=value){ + _SomeFlag=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SomeFlag"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + bool? _SomeNullableFlag; + public bool? SomeNullableFlag + { + get { return _SomeNullableFlag; } + set + { + if(_SomeNullableFlag!=value){ + _SomeNullableFlag=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SomeNullableFlag"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _LongText; + public string LongText + { + get { return _LongText; } + set + { + if(_LongText!=value){ + _LongText=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="LongText"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _MediumText; + public string MediumText + { + get { return _MediumText; } + set + { + if(_MediumText!=value){ + _MediumText=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MediumText"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + this.CreatedOn=DateTime.Now; + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Products table in the Northwind Database. + /// + public partial class Product: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Product item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Product(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Product.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Product(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Product(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Product.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Product SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Product single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Product SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Product single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "ProductID"; + } + + public object KeyValue() + { + return this.ProductID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.ProductName.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Product)){ + Product compare=(Product)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.ProductName.ToString(); + } + + public string DescriptorColumn() { + return "ProductName"; + } + public static string GetKeyColumn() + { + return "ProductID"; + } + public static string GetDescriptorColumn() + { + return "ProductName"; + } + + #region ' Foreign Keys ' + public IQueryable Categories + { + get + { + + var repo=SouthWind.Category.GetRepo(); + return from items in repo.GetAll() + where items.CategoryID == _CategoryID + select items; + } + } + + public IQueryable OrderDetails + { + get + { + + var repo=SouthWind.OrderDetail.GetRepo(); + return from items in repo.GetAll() + where items.ProductID == _ProductID + select items; + } + } + + public IQueryable Suppliers + { + get + { + + var repo=SouthWind.Supplier.GetRepo(); + return from items in repo.GetAll() + where items.SupplierID == _SupplierID + select items; + } + } + + #endregion + + + int _ProductID; + public int ProductID + { + get { return _ProductID; } + set + { + if(_ProductID!=value){ + _ProductID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ProductID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _ProductName; + public string ProductName + { + get { return _ProductName; } + set + { + if(_ProductName!=value){ + _ProductName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ProductName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + int? _SupplierID; + public int? SupplierID + { + get { return _SupplierID; } + set + { + if(_SupplierID!=value){ + _SupplierID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SupplierID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + int? _CategoryID; + public int? CategoryID + { + get { return _CategoryID; } + set + { + if(_CategoryID!=value){ + _CategoryID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CategoryID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _QuantityPerUnit; + public string QuantityPerUnit + { + get { return _QuantityPerUnit; } + set + { + if(_QuantityPerUnit!=value){ + _QuantityPerUnit=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="QuantityPerUnit"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + decimal? _UnitPrice; + public decimal? UnitPrice + { + get { return _UnitPrice; } + set + { + if(_UnitPrice!=value){ + _UnitPrice=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="UnitPrice"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + short? _UnitsInStock; + public short? UnitsInStock + { + get { return _UnitsInStock; } + set + { + if(_UnitsInStock!=value){ + _UnitsInStock=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="UnitsInStock"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + long? _UnitsOnOrder; + public long? UnitsOnOrder + { + get { return _UnitsOnOrder; } + set + { + if(_UnitsOnOrder!=value){ + _UnitsOnOrder=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="UnitsOnOrder"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + short? _ReorderLevel; + public short? ReorderLevel + { + get { return _ReorderLevel; } + set + { + if(_ReorderLevel!=value){ + _ReorderLevel=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ReorderLevel"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + bool _Discontinued; + public bool Discontinued + { + get { return _Discontinued; } + set + { + if(_Discontinued!=value){ + _Discontinued=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Discontinued"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Employees table in the Northwind Database. + /// + public partial class Employee: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Employee item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Employee(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Employee.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Employee(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Employee(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Employee.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Employee SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Employee single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Employee SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Employee single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "EmployeeID"; + } + + public object KeyValue() + { + return this.EmployeeID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.LastName.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Employee)){ + Employee compare=(Employee)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.LastName.ToString(); + } + + public string DescriptorColumn() { + return "LastName"; + } + public static string GetKeyColumn() + { + return "EmployeeID"; + } + public static string GetDescriptorColumn() + { + return "LastName"; + } + + #region ' Foreign Keys ' + public IQueryable Employees + { + get + { + + var repo=SouthWind.Employee.GetRepo(); + return from items in repo.GetAll() + where items.EmployeeID == _ReportsTo + select items; + } + } + + public IQueryable EmployeeTerritories + { + get + { + + var repo=SouthWind.EmployeeTerritory.GetRepo(); + return from items in repo.GetAll() + where items.EmployeeID == _EmployeeID + select items; + } + } + + public IQueryable Orders + { + get + { + + var repo=SouthWind.Order.GetRepo(); + return from items in repo.GetAll() + where items.EmployeeID == _EmployeeID + select items; + } + } + + #endregion + + + int _EmployeeID; + public int EmployeeID + { + get { return _EmployeeID; } + set + { + if(_EmployeeID!=value){ + _EmployeeID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EmployeeID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _LastName; + public string LastName + { + get { return _LastName; } + set + { + if(_LastName!=value){ + _LastName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="LastName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _FirstName; + public string FirstName + { + get { return _FirstName; } + set + { + if(_FirstName!=value){ + _FirstName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="FirstName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Title; + public string Title + { + get { return _Title; } + set + { + if(_Title!=value){ + _Title=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Title"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _TitleOfCourtesy; + public string TitleOfCourtesy + { + get { return _TitleOfCourtesy; } + set + { + if(_TitleOfCourtesy!=value){ + _TitleOfCourtesy=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="TitleOfCourtesy"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + DateTime? _BirthDate; + public DateTime? BirthDate + { + get { return _BirthDate; } + set + { + if(_BirthDate!=value){ + _BirthDate=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BirthDate"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + DateTime? _HireDate; + public DateTime? HireDate + { + get { return _HireDate; } + set + { + if(_HireDate!=value){ + _HireDate=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="HireDate"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Address; + public string Address + { + get { return _Address; } + set + { + if(_Address!=value){ + _Address=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Address"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _City; + public string City + { + get { return _City; } + set + { + if(_City!=value){ + _City=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="City"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Region; + public string Region + { + get { return _Region; } + set + { + if(_Region!=value){ + _Region=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Region"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _PostalCode; + public string PostalCode + { + get { return _PostalCode; } + set + { + if(_PostalCode!=value){ + _PostalCode=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="PostalCode"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Country; + public string Country + { + get { return _Country; } + set + { + if(_Country!=value){ + _Country=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Country"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _HomePhone; + public string HomePhone + { + get { return _HomePhone; } + set + { + if(_HomePhone!=value){ + _HomePhone=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="HomePhone"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Extension; + public string Extension + { + get { return _Extension; } + set + { + if(_Extension!=value){ + _Extension=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Extension"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + byte[] _Photo; + public byte[] Photo + { + get { return _Photo; } + set + { + if(_Photo!=value){ + _Photo=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Photo"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Notes; + public string Notes + { + get { return _Notes; } + set + { + if(_Notes!=value){ + _Notes=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Notes"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + int? _ReportsTo; + public int? ReportsTo + { + get { return _ReportsTo; } + set + { + if(_ReportsTo!=value){ + _ReportsTo=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ReportsTo"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _PhotoPath; + public string PhotoPath + { + get { return _PhotoPath; } + set + { + if(_PhotoPath!=value){ + _PhotoPath=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="PhotoPath"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } + + + /// + /// A class which represents the Categories table in the Northwind Database. + /// + public partial class Category: IActiveRecord + { + + #region Built-in testing + static IList TestItems; + static TestRepository _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository(new SouthWind.NorthwindDB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(Category item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + SouthWind.NorthwindDB _db; + public Category(string connectionString, string providerName) { + + _db=new SouthWind.NorthwindDB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + Category.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public Category(){ + _db=new SouthWind.NorthwindDB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public Category(Expression> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository GetRepo(string connectionString, string providerName){ + SouthWind.NorthwindDB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new SouthWind.NorthwindDB(); + }else{ + db=new SouthWind.NorthwindDB(connectionString, providerName); + } + IRepository _repo; + + if(db.TestMode){ + Category.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository(db); + } + return _repo; + } + + internal static IRepository GetRepo(){ + return GetRepo("",""); + } + + public static Category SingleOrDefault(Expression> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + Category single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static Category SingleOrDefault(Expression> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + Category single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression> expression) { + + return All().Any(expression); + } + + public static IList Find(Expression> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList Find(Expression> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable All() { + return GetRepo().GetAll(); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "CategoryID"; + } + + public object KeyValue() + { + return this.CategoryID; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.CategoryName.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(Category)){ + Category compare=(Category)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.CategoryName.ToString(); + } + + public string DescriptorColumn() { + return "CategoryName"; + } + public static string GetKeyColumn() + { + return "CategoryID"; + } + public static string GetDescriptorColumn() + { + return "CategoryName"; + } + + #region ' Foreign Keys ' + public IQueryable Products + { + get + { + + var repo=SouthWind.Product.GetRepo(); + return from items in repo.GetAll() + where items.CategoryID == _CategoryID + select items; + } + } + + #endregion + + + int _CategoryID; + public int CategoryID + { + get { return _CategoryID; } + set + { + if(_CategoryID!=value){ + _CategoryID=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CategoryID"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _CategoryName; + public string CategoryName + { + get { return _CategoryName; } + set + { + if(_CategoryName!=value){ + _CategoryName=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CategoryName"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + string _Description; + public string Description + { + get { return _Description; } + set + { + if(_Description!=value){ + _Description=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Description"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + byte[] _Picture; + public byte[] Picture + { + get { return _Picture; } + set + { + if(_Picture!=value){ + _Picture=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Picture"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + + + + public DbCommand GetUpdateCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + + + public void Add(IDataProvider provider){ + + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + + + public void Delete(IDataProvider provider) { + + + _repo.Delete(KeyValue()); + + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression> expression) { + var repo = GetRepo(); + + + + repo.DeleteMany(expression); + + } + + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } +} diff --git a/SubSonic.Tests/BugReports/Generated/ActiveRecord.tt b/SubSonic.Tests/BugReports/Generated/ActiveRecord.tt new file mode 100644 index 0000000..125bcaf --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/ActiveRecord.tt @@ -0,0 +1,599 @@ +<#@ template language="C#v3.5" debug="True" hostspecific="True" #> +<#@ include file="SQLServer.ttinclude" #> +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Data; +using SubSonic.DataProviders; +using SubSonic.Extensions; +using System.Linq.Expressions; +using SubSonic.Schema; +using System.Collections; +using SubSonic; +using SubSonic.Repository; +using System.ComponentModel; +using System.Data.Common; + +namespace <#=Namespace #> +{ +<# + + var tables = LoadTables(); + + foreach(Table tbl in tables) + { + if(!ExcludeTables.Contains(tbl.Name)) + { +#> + + + /// + /// A class which represents the <#=tbl.Name #> table in the <#=DatabaseName#> Database. + /// + public partial class <#=tbl.ClassName#>: IActiveRecord + { + + #region Built-in testing + static IList<<#=tbl.ClassName#>> TestItems; + static TestRepository<<#=tbl.ClassName#>> _testRepo; + + + + static void SetTestRepo(){ + _testRepo = _testRepo ?? new TestRepository<<#=tbl.ClassName#>>(new <#=Namespace#>.<#=DatabaseName#>DB()); + } + public static void ResetTestRepo(){ + _testRepo = null; + SetTestRepo(); + } + public static void Setup(List<<#=tbl.ClassName#>> testlist){ + SetTestRepo(); + _testRepo._items = testlist; + } + public static void Setup(<#=tbl.ClassName#> item) { + SetTestRepo(); + _testRepo._items.Add(item); + } + public static void Setup(int testItems) { + SetTestRepo(); + for(int i=0;i item=new <#=tbl.ClassName#>(); + _testRepo._items.Add(item); + } + } + + public bool TestMode = false; + + + #endregion + + IRepository<<#=tbl.ClassName#>> _repo; + ITable tbl; + bool _isNew; + public bool IsNew(){ + return _isNew; + } + + public void SetIsLoaded(bool isLoaded){ + _isLoaded=isLoaded; + if(isLoaded) + OnLoaded(); + } + + public void SetIsNew(bool isNew){ + _isNew=isNew; + } + bool _isLoaded; + public bool IsLoaded(){ + return _isLoaded; + } + + List _dirtyColumns; + public bool IsDirty(){ + return _dirtyColumns.Count>0; + } + + public List GetDirtyColumns (){ + return _dirtyColumns; + } + + <#=Namespace#>.<#=DatabaseName#>DB _db; + public <#=tbl.ClassName#>(string connectionString, string providerName) { + + _db=new <#=Namespace#>.<#=DatabaseName#>DB(connectionString, providerName); + Init(); + } + void Init(){ + TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + _dirtyColumns=new List(); + if(TestMode){ + <#=tbl.ClassName#>.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository<<#=tbl.ClassName#>>(_db); + } + tbl=_repo.GetTable(); + SetIsNew(true); + OnCreated(); + + } + + public <#=tbl.ClassName#>(){ + _db=new <#=Namespace#>.<#=DatabaseName#>DB(); + Init(); + } + + + partial void OnCreated(); + + partial void OnLoaded(); + + partial void OnSaved(); + + partial void OnChanged(); + + public IList Columns{ + get{ + return tbl.Columns; + } + } + + public <#=tbl.ClassName#>(Expression, bool>> expression):this() { + + SetIsLoaded(_repo.Load(this,expression)); + } + + + + internal static IRepository<<#=tbl.ClassName#>> GetRepo(string connectionString, string providerName){ + <#=Namespace#>.<#=DatabaseName#>DB db; + if(String.IsNullOrEmpty(connectionString)){ + db=new <#=Namespace#>.<#=DatabaseName#>DB(); + }else{ + db=new <#=Namespace#>.<#=DatabaseName#>DB(connectionString, providerName); + } + IRepository<<#=tbl.ClassName#>> _repo; + + if(db.TestMode){ + <#=tbl.ClassName#>.SetTestRepo(); + _repo=_testRepo; + }else{ + _repo = new SubSonicRepository<<#=tbl.ClassName#>>(db); + } + return _repo; + } + + internal static IRepository<<#=tbl.ClassName#>> GetRepo(){ + return GetRepo("",""); + } + + public static <#=tbl.ClassName#> SingleOrDefault(Expression, bool>> expression) { + + var repo = GetRepo(); + var results=repo.Find(expression); + <#=tbl.ClassName#> single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + single.OnLoaded(); + single.SetIsLoaded(true); + single.SetIsNew(false); + } + + return single; + } + + public static <#=tbl.ClassName#> SingleOrDefault(Expression, bool>> expression,string connectionString, string providerName) { + var repo = GetRepo(connectionString,providerName); + var results=repo.Find(expression); + <#=tbl.ClassName#> single=null; + if(results.Count() > 0){ + single=results.ToList()[0]; + } + + return single; + + + } + + + public static bool Exists(Expression, bool>> expression,string connectionString, string providerName) { + + return All(connectionString,providerName).Any(expression); + } + public static bool Exists(Expression, bool>> expression) { + + return All().Any(expression); + } + + public static IList<<#=tbl.ClassName#>> Find(Expression, bool>> expression) { + + var repo = GetRepo(); + return repo.Find(expression).ToList(); + } + + public static IList<<#=tbl.ClassName#>> Find(Expression, bool>> expression,string connectionString, string providerName) { + + var repo = GetRepo(connectionString,providerName); + return repo.Find(expression).ToList(); + + } + public static IQueryable<<#=tbl.ClassName#>> All(string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetAll(); + } + public static IQueryable<<#=tbl.ClassName#>> All() { + return GetRepo().GetAll(); + } + + public static PagedList<<#=tbl.ClassName#>> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList<<#=tbl.ClassName#>> GetPaged(string sortBy, int pageIndex, int pageSize) { + return GetRepo().GetPaged(sortBy, pageIndex, pageSize); + } + + public static PagedList<<#=tbl.ClassName#>> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { + return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); + + } + + + public static PagedList<<#=tbl.ClassName#>> GetPaged(int pageIndex, int pageSize) { + return GetRepo().GetPaged(pageIndex, pageSize); + + } + + public string KeyName() + { + return "<#=tbl.PK.CleanName #>"; + } + + public object KeyValue() + { + return this.<#=tbl.PK.CleanName#>; + } + + public void SetKeyValue(object value) { + if (value != null && value!=DBNull.Value) { + var settable = value.ChangeTypeTo<<#=tbl.PK.SysType#>>(); + this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); + } + } + + public override string ToString(){ + return this.<#=tbl.Descriptor.CleanName #>.ToString(); + } + + public override bool Equals(object obj){ + if(obj.GetType()==typeof(<#=tbl.ClassName#>)){ + <#=tbl.ClassName#> compare=(<#=tbl.ClassName#>)obj; + return compare.KeyValue()==this.KeyValue(); + }else{ + return base.Equals(obj); + } + } + + public string DescriptorValue() + { + return this.<#=tbl.Descriptor.CleanName #>.ToString(); + } + + public string DescriptorColumn() { + return "<#=tbl.Descriptor.CleanName #>"; + } + public static string GetKeyColumn() + { + return "<#=tbl.PK.CleanName #>"; + } + public static string GetDescriptorColumn() + { + return "<#=tbl.Descriptor.CleanName #>"; + } + + #region ' Foreign Keys ' +<# + List fkCreated = new List(); + foreach(FKTable fk in tbl.FKTables) + { + + if(!ExcludeTables.Contains(fk.OtherTable)){ + string propName=fk.OtherQueryable; + if(fkCreated.Contains(propName)) + { + propName=fk.OtherQueryable+fkCreated.Count.ToString(); + } + + fkCreated.Add(fk.OtherQueryable); + + +#> + public IQueryable<<#=fk.OtherClass #>> <#=propName #> + { + get + { + + var repo=<#=Namespace #>.<#=fk.OtherClass#>.GetRepo(); + return from items in repo.GetAll() + where items.<#=CleanUp(fk.OtherColumn)#> == _<#=CleanUp(fk.ThisColumn)#> + select items; + } + } + +<# + } + } + +#> + #endregion + + +<# + foreach(Column col in tbl.Columns) + { + + if (tbl.ClassName == col.CleanName) + { + col.CleanName += "X"; + } +#> + <#=col.SysType #><#=CheckNullable(col)#> _<#=col.CleanName #>; + public <#=col.SysType #><#=CheckNullable(col)#> <#=col.CleanName #> + { + get { return _<#=col.CleanName #>; } + set + { + if(_<#=col.CleanName #>!=value){ + _<#=col.CleanName #>=value; + var col=tbl.Columns.SingleOrDefault(x=>x.Name=="<#=col.Name #>"); + if(col!=null){ + if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ + _dirtyColumns.Add(col); + } + } + OnChanged(); + } + } + } + +<# + } +#> + + + public DbCommand GetUpdateCommand() { +<#if(tbl.Columns.Any(x=>x.Name.ToLower()=="modifiedon")){#> + if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) { + this.<#=tbl.Columns.Single(x=>x.Name.ToLower()=="modifiedon").CleanName#>=DateTime.Now; + } +<#}#> + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); + + } + public DbCommand GetInsertCommand() { + + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + public DbCommand GetDeleteCommand() { + if(TestMode) + return _db.DataProvider.CreateCommand(); + else + return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); + } + + + public void Update(){ + Update(_db.DataProvider); + } + + public void Update(IDataProvider provider){ + +<#if(tbl.Columns.Any(x=>x.Name=="ModifiedBy")){#> + if(String.IsNullOrEmpty(this.ModifiedBy)) + this.ModifiedBy=Environment.UserName; +<#}#> +<#if(tbl.Columns.Any(x=>x.Name=="ModifiedOn")){#> + this.ModifiedOn=DateTime.Now; +<#}#> + + if(this._dirtyColumns.Count>0) + _repo.Update(this,provider); + OnSaved(); + } + + public void Add(){ + Add(_db.DataProvider); + } + + <#if(tbl.Columns.Any(x=>x.Name=="ModifiedBy")){#> + public void Update(string username){ + + this.ModifiedBy=username; + Update(); + + } + public void Update(string username, IDataProvider provider){ + + this.ModifiedBy=username; + Update(provider); + } + <#}#> + + + public void Add(IDataProvider provider){ + +<#if(tbl.Columns.Any(x=>x.Name=="CreatedOn")){#> + + this.CreatedOn=DateTime.Now; +<#}#> +<#if(tbl.Columns.Any(x=>x.Name=="CreatedBy")){#> + if(String.IsNullOrEmpty(this.CreatedBy)) + this.CreatedBy=Environment.UserName; +<#}#> +<#if(tbl.Columns.Any(x=>x.Name=="ModifiedOn")){#> + this.ModifiedOn=DateTime.Now; +<#}#> +<#if(tbl.Columns.Any(x=>x.Name=="ModifiedBy")){#> + if(String.IsNullOrEmpty(this.ModifiedBy)) + this.ModifiedBy=Environment.UserName; +<#}#> + + var newKey=_repo.Add(this,provider); + if(newKey!=KeyValue()) + this.SetKeyValue(newKey); + + SetIsNew(false); + OnSaved(); + } + + <#if(tbl.Columns.Any(x=>x.Name=="CreatedBy")){#> + public void Add(string username){ + + this.CreatedBy=username; + Add(); + + } + public void Add(string username, IDataProvider provider){ + + this.CreatedBy=username; + Add(provider); + } + <#}#> + + + public void Save() { + Save(_db.DataProvider); + } + public void Save(IDataProvider provider) { + + + if (_isNew) { + Add(provider); + + } else { + Update(provider); + } + + } + + <#if(tbl.Columns.Any(x=>x.Name=="CreatedBy" || x.Name=="ModifiedBy")){#> + public void Save(string username, IDataProvider provider) { + + + if (_isNew) { + <#if(tbl.Columns.Any(x=>x.Name=="CreatedBy")){#> + Add(username,provider); + <#}else{#> + Add(provider); + <#}#> + } else { + <#if(tbl.Columns.Any(x=>x.Name=="ModifiedBy")){#> + Update(username,provider); + <#}else{#> + Update(provider); + <#}#> + + } + + } + <#}#> + + + public void Delete(IDataProvider provider) { + <#if(tbl.HasLogicalDelete()){#> + + this.<#=tbl.DeleteColumn.CleanName#>=true; + _repo.Update(this,provider); + + <#}else{#> + + _repo.Delete(KeyValue()); + + <#}#> + } + + + public void Delete() { + Delete(_db.DataProvider); + } + + + public static void Delete(Expression, bool>> expression) { + var repo = GetRepo(); + +<#if(tbl.HasLogicalDelete()){#> + + List<<#=tbl.ClassName#>> items=repo.GetAll().Where(expression).ToList(); + items.ForEach(x=>x.<#=tbl.DeleteColumn.CleanName#>=true); + repo.Update(items); + +<#}else{#> + + repo.DeleteMany(expression); + +<#}#> + } + + <#if(tbl.HasLogicalDelete()){#> + + public static void Destroy(Func<<#=tbl.ClassName#>, bool> expression) { + var repo = GetRepo(); + repo.Delete(expression); + } + + public static void Destroy(object key) { + var repo = GetRepo(); + repo.Delete(key); + } + + public static void Destroy(object key, IDataProvider provider) { + + var repo = GetRepo(); + repo.Delete(key,provider); + + } + + public void Destroy() { + _repo.Delete(KeyValue()); + } + public void Destroy(IDataProvider provider) { + _repo.Delete(KeyValue(), provider); + } + <#}#> + + + public void Load(IDataReader rdr) { + Load(rdr, true); + } + public void Load(IDataReader rdr, bool closeReader) { + if (rdr.Read()) { + + try { + rdr.Load(this); + SetIsNew(false); + SetIsLoaded(true); + } catch { + SetIsLoaded(false); + throw; + } + }else{ + SetIsLoaded(false); + } + + if (closeReader) + rdr.Dispose(); + } + + + } +<# } + } +#> +} diff --git a/SubSonic.Tests/BugReports/Generated/Context.cs b/SubSonic.Tests/BugReports/Generated/Context.cs new file mode 100644 index 0000000..424c371 --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/Context.cs @@ -0,0 +1,280 @@ + + + +using System; +using System.Data; +using System.Linq; +using System.Linq.Expressions; +using SubSonic.DataProviders; +using SubSonic.Extensions; +using SubSonic.Linq.Structure; +using SubSonic.Query; +using SubSonic.Schema; +using System.Data.Common; +using System.Collections.Generic; + +namespace SouthWind +{ + public partial class NorthwindDB : IQuerySurface + { + + public IDataProvider DataProvider; + public DbQueryProvider provider; + + public bool TestMode + { + get + { + return DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + } + } + + public NorthwindDB() + { + DataProvider = ProviderFactory.GetProvider("Northwind"); + Init(); + } + + public NorthwindDB(string connectionStringName) + { + DataProvider = ProviderFactory.GetProvider(connectionStringName); + Init(); + } + + public NorthwindDB(string connectionString, string providerName) + { + DataProvider = ProviderFactory.GetProvider(connectionString,providerName); + Init(); + } + + public ITable FindByPrimaryKey(string pkName) + { + return DataProvider.Schema.Tables.SingleOrDefault(x => x.PrimaryKey.Name.Equals(pkName, StringComparison.InvariantCultureIgnoreCase)); + } + + public Query GetQuery() + { + return new Query(provider); + } + + public ITable FindTable(string tableName) + { + return DataProvider.FindTable(tableName); + } + + public IDataProvider Provider + { + get { return DataProvider; } + set {DataProvider=value;} + } + + public DbQueryProvider QueryProvider + { + get { return provider; } + } + + BatchQuery _batch = null; + public void Queue(IQueryable qry) + { + if (_batch == null) + _batch = new BatchQuery(Provider, QueryProvider); + _batch.Queue(qry); + } + + public void Queue(ISqlQuery qry) + { + if (_batch == null) + _batch = new BatchQuery(Provider, QueryProvider); + _batch.Queue(qry); + } + + public void ExecuteTransaction(IList commands) + { + if(!TestMode) + { + using(var connection = commands[0].Connection) + { + if (connection.State == ConnectionState.Closed) + connection.Open(); + + using (var trans = connection.BeginTransaction()) + { + foreach (var cmd in commands) + { + cmd.Transaction = trans; + cmd.Connection = connection; + cmd.ExecuteNonQuery(); + } + trans.Commit(); + } + connection.Close(); + } + } + } + + public IDataReader ExecuteBatch() + { + if (_batch == null) + throw new InvalidOperationException("There's nothing in the queue"); + if(!TestMode) + return _batch.ExecuteReader(); + return null; + } + + public Query Customers { get; set; } + public Query Shippers { get; set; } + public Query Suppliers { get; set; } + public Query OrderDetails { get; set; } + public Query CustomerCustomerDemos { get; set; } + public Query CustomerDemographics { get; set; } + public Query Regions { get; set; } + public Query Territories { get; set; } + public Query EmployeeTerritories { get; set; } + public Query Orders { get; set; } + public Query SubSonicTests { get; set; } + public Query Products { get; set; } + public Query Employees { get; set; } + public Query Categories { get; set; } + + + + #region ' Aggregates and SubSonic Queries ' + public Select SelectColumns(params string[] columns) + { + return new Select(DataProvider, columns); + } + + public Select Select + { + get { return new Select(this.Provider); } + } + + public Insert Insert + { + get { return new Insert(this.Provider); } + } + + public Update Update() where T:new() + { + return new Update(this.Provider); + } + + public SqlQuery Delete(Expression> column) where T:new() + { + LambdaExpression lamda = column; + SqlQuery result = new Delete(this.Provider); + result = result.From(); + SubSonic.Query.Constraint c = lamda.ParseConstraint(); + result.Constraints.Add(c); + return result; + } + + public SqlQuery Max(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = DataProvider.FindTable(objectName).Name; + return new Select(DataProvider, new Aggregate(colName, AggregateFunction.Max)).From(tableName); + } + + public SqlQuery Min(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Min)).From(tableName); + } + + public SqlQuery Sum(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Sum)).From(tableName); + } + + public SqlQuery Avg(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Avg)).From(tableName); + } + + public SqlQuery Count(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Count)).From(tableName); + } + + public SqlQuery Variance(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Var)).From(tableName); + } + + public SqlQuery StandardDeviation(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.StDev)).From(tableName); + } + + #endregion + + void Init() + { + provider = new DbQueryProvider(this.Provider); + + #region ' Query Defs ' + Customers = new Query(provider); + Shippers = new Query(provider); + Suppliers = new Query(provider); + OrderDetails = new Query(provider); + CustomerCustomerDemos = new Query(provider); + CustomerDemographics = new Query(provider); + Regions = new Query(provider); + Territories = new Query(provider); + EmployeeTerritories = new Query(provider); + Orders = new Query(provider); + SubSonicTests = new Query(provider); + Products = new Query(provider); + Employees = new Query(provider); + Categories = new Query(provider); + #endregion + + + #region ' Schemas ' + if(DataProvider.Schema.Tables.Count == 0) + { + DataProvider.Schema.Tables.Add(new CustomersTable(DataProvider)); + DataProvider.Schema.Tables.Add(new ShippersTable(DataProvider)); + DataProvider.Schema.Tables.Add(new SuppliersTable(DataProvider)); + DataProvider.Schema.Tables.Add(new OrderDetailsTable(DataProvider)); + DataProvider.Schema.Tables.Add(new CustomerCustomerDemoTable(DataProvider)); + DataProvider.Schema.Tables.Add(new CustomerDemographicsTable(DataProvider)); + DataProvider.Schema.Tables.Add(new RegionTable(DataProvider)); + DataProvider.Schema.Tables.Add(new TerritoriesTable(DataProvider)); + DataProvider.Schema.Tables.Add(new EmployeeTerritoriesTable(DataProvider)); + DataProvider.Schema.Tables.Add(new OrdersTable(DataProvider)); + DataProvider.Schema.Tables.Add(new SubSonicTestsTable(DataProvider)); + DataProvider.Schema.Tables.Add(new ProductsTable(DataProvider)); + DataProvider.Schema.Tables.Add(new EmployeesTable(DataProvider)); + DataProvider.Schema.Tables.Add(new CategoriesTable(DataProvider)); + } + #endregion + } + } +} \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/Generated/Context.tt b/SubSonic.Tests/BugReports/Generated/Context.tt new file mode 100644 index 0000000..c60b277 --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/Context.tt @@ -0,0 +1,277 @@ +<#@ template language="C#v3.5" debug="False" hostspecific="True" #> +<#@ output extension=".cs" #> +<#@ include file="SQLServer.ttinclude" #> +<# + var tables = LoadTables(); +#> +using System; +using System.Data; +using System.Linq; +using System.Linq.Expressions; +using SubSonic.DataProviders; +using SubSonic.Extensions; +using SubSonic.Linq.Structure; +using SubSonic.Query; +using SubSonic.Schema; +using System.Data.Common; +using System.Collections.Generic; + +namespace <#=Namespace#> +{ + public partial class <#=DatabaseName#>DB : IQuerySurface + { + + public IDataProvider DataProvider; + public DbQueryProvider provider; + + public bool TestMode + { + get + { + return DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); + } + } + + public <#=DatabaseName#>DB() + { + DataProvider = ProviderFactory.GetProvider("<#=ConnectionStringName#>"); + Init(); + } + + public <#=DatabaseName#>DB(string connectionStringName) + { + DataProvider = ProviderFactory.GetProvider(connectionStringName); + Init(); + } + + public <#=DatabaseName#>DB(string connectionString, string providerName) + { + DataProvider = ProviderFactory.GetProvider(connectionString,providerName); + Init(); + } + + public ITable FindByPrimaryKey(string pkName) + { + return DataProvider.Schema.Tables.SingleOrDefault(x => x.PrimaryKey.Name.Equals(pkName, StringComparison.InvariantCultureIgnoreCase)); + } + + public Query GetQuery() + { + return new Query(provider); + } + + public ITable FindTable(string tableName) + { + return DataProvider.FindTable(tableName); + } + + public IDataProvider Provider + { + get { return DataProvider; } + set {DataProvider=value;} + } + + public DbQueryProvider QueryProvider + { + get { return provider; } + } + + BatchQuery _batch = null; + public void Queue(IQueryable qry) + { + if (_batch == null) + _batch = new BatchQuery(Provider, QueryProvider); + _batch.Queue(qry); + } + + public void Queue(ISqlQuery qry) + { + if (_batch == null) + _batch = new BatchQuery(Provider, QueryProvider); + _batch.Queue(qry); + } + + public void ExecuteTransaction(IList commands) + { + if(!TestMode) + { + using(var connection = commands[0].Connection) + { + if (connection.State == ConnectionState.Closed) + connection.Open(); + + using (var trans = connection.BeginTransaction()) + { + foreach (var cmd in commands) + { + cmd.Transaction = trans; + cmd.Connection = connection; + cmd.ExecuteNonQuery(); + } + trans.Commit(); + } + connection.Close(); + } + } + } + + public IDataReader ExecuteBatch() + { + if (_batch == null) + throw new InvalidOperationException("There's nothing in the queue"); + if(!TestMode) + return _batch.ExecuteReader(); + return null; + } +<# //################################################ IQueryable ####################################### #> +<# foreach(Table tbl in tables){ + if(!ExcludeTables.Contains(tbl.Name)) + { +#> + public Query<<#=tbl.ClassName#>> <#=tbl.QueryableName#> { get; set; } +<# + } + } +#> + +<# //################################################ Aggregates and Queries ####################################### #> + + #region ' Aggregates and SubSonic Queries ' + public Select SelectColumns(params string[] columns) + { + return new Select(DataProvider, columns); + } + + public Select Select + { + get { return new Select(this.Provider); } + } + + public Insert Insert + { + get { return new Insert(this.Provider); } + } + + public Update Update() where T:new() + { + return new Update(this.Provider); + } + + public SqlQuery Delete(Expression> column) where T:new() + { + LambdaExpression lamda = column; + SqlQuery result = new Delete(this.Provider); + result = result.From(); + SubSonic.Query.Constraint c = lamda.ParseConstraint(); + result.Constraints.Add(c); + return result; + } + + public SqlQuery Max(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = DataProvider.FindTable(objectName).Name; + return new Select(DataProvider, new Aggregate(colName, AggregateFunction.Max)).From(tableName); + } + + public SqlQuery Min(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Min)).From(tableName); + } + + public SqlQuery Sum(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Sum)).From(tableName); + } + + public SqlQuery Avg(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Avg)).From(tableName); + } + + public SqlQuery Count(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Count)).From(tableName); + } + + public SqlQuery Variance(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Var)).From(tableName); + } + + public SqlQuery StandardDeviation(Expression> column) + { + LambdaExpression lamda = column; + string colName = lamda.ParseObjectValue(); + string objectName = typeof(T).Name; + string tableName = this.Provider.FindTable(objectName).Name; + return new Select(this.Provider, new Aggregate(colName, AggregateFunction.StDev)).From(tableName); + } + + #endregion + + void Init() + { + provider = new DbQueryProvider(this.Provider); + +<# + //################################################ QUERIES ####################################### #> + #region ' Query Defs ' +<# + foreach(Table tbl in tables) + { + if(!ExcludeTables.Contains(tbl.Name)) + { +#> + <#=tbl.QueryableName#> = new Query<<#=tbl.ClassName#>>(provider); +<# + } +#> +<# + } +#> + #endregion + +<#//################################################ SCHEMAS ####################################### #> + + #region ' Schemas ' + if(DataProvider.Schema.Tables.Count == 0) + { +<# + foreach(Table tbl in tables) + { + if(!ExcludeTables.Contains(tbl.Name)) + { +#> + DataProvider.Schema.Tables.Add(new <#=tbl.CleanName#>Table(DataProvider)); +<# + } + } +#> + } + #endregion + } + } +} \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/Generated/SQLServer.ttinclude b/SubSonic.Tests/BugReports/Generated/SQLServer.ttinclude new file mode 100644 index 0000000..6036677 --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/SQLServer.ttinclude @@ -0,0 +1,333 @@ +<#@ include file="Settings.ttinclude" #> +<#+ + +IDataReader GetReader(string sql){ + SqlConnection conn=new SqlConnection(ConnectionString); + SqlCommand cmd=new SqlCommand(sql,conn); + conn.Open(); + return cmd.ExecuteReader(CommandBehavior.CloseConnection); +} +SqlCommand GetCommand(string sql){ + SqlConnection conn=new SqlConnection(ConnectionString); + SqlCommand cmd=new SqlCommand(sql,conn); + conn.Open(); + return cmd; +} + +const string FKSql=@"SELECT + ThisTable = FK.TABLE_NAME, + ThisColumn = CU.COLUMN_NAME, + OtherTable = PK.TABLE_NAME, + OtherColumn = PT.COLUMN_NAME, + Constraint_Name = C.CONSTRAINT_NAME, + Owner = FK.TABLE_SCHEMA + FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C + INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME + INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME + INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME + INNER JOIN + ( + SELECT i1.TABLE_NAME, i2.COLUMN_NAME + FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 + INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME + WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' + ) + PT ON PT.TABLE_NAME = PK.TABLE_NAME + WHERE FK.Table_NAME=@tableName OR PK.Table_NAME=@tableName"; + + +const string TABLE_SQL=@"SELECT * + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_TYPE='BASE TABLE'"; + +const string COLUMN_SQL=@"SELECT + TABLE_CATALOG AS [Database], + TABLE_SCHEMA AS Owner, + TABLE_NAME AS TableName, + COLUMN_NAME AS ColumnName, + ORDINAL_POSITION AS OrdinalPosition, + COLUMN_DEFAULT AS DefaultSetting, + IS_NULLABLE AS IsNullable, DATA_TYPE AS DataType, + CHARACTER_MAXIMUM_LENGTH AS MaxLength, + DATETIME_PRECISION AS DatePrecision, + COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsIdentity') AS IsIdentity, + COLUMNPROPERTY(object_id('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'), COLUMN_NAME, 'IsComputed') as IsComputed + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_NAME=@tableName + ORDER BY OrdinalPosition ASC"; + + +List GetSPParams(string spName){ + var result=new List(); + string[] restrictions = new string[4] { DatabaseName, null, spName, null }; + using(SqlConnection conn=new SqlConnection(ConnectionString)){ + conn.Open(); + var sprocs=conn.GetSchema("ProcedureParameters", restrictions); + conn.Close(); + foreach(DataRow row in sprocs.Rows){ + SPParam p=new SPParam(); + p.SysType=GetSysType(row["DATA_TYPE"].ToString()); + p.DbType=GetDbType(row["DATA_TYPE"].ToString()).ToString(); + p.Name=row["PARAMETER_NAME"].ToString().Replace("@",""); + p.CleanName=CleanUp(p.Name); + result.Add(p); + } + + + } + return result; +} +List GetSPs(){ + var result=new List(); + //pull the SPs + + DataTable sprocs=null; + DataTable parameters=null; + + using(SqlConnection conn=new SqlConnection(ConnectionString)){ + conn.Open(); + sprocs=conn.GetSchema("Procedures"); + conn.Close(); + } + + foreach(DataRow row in sprocs.Rows){ + string spType=row["ROUTINE_TYPE"].ToString(); + var sp=new SP(); + sp.Name=row["ROUTINE_NAME"].ToString(); + + if(spType=="PROCEDURE" &! sp.Name.StartsWith("sp_")){ + + sp.CleanName=CleanUp(sp.Name); + + sp.Parameters=GetSPParams(sp.Name); + result.Add(sp); + } + } + return result; + +} + + +List LoadTables(){ + var result=new List
(); + + //pull the tables in a reader + using(IDataReader rdr=GetReader(TABLE_SQL)){ + while(rdr.Read()){ + Table tbl=new Table(); + tbl.Name=rdr["TABLE_NAME"].ToString(); + tbl.Schema=rdr["TABLE_SCHEMA"].ToString(); + tbl.Columns=LoadColumns(tbl); + tbl.PrimaryKey=GetPK(tbl.Name); + tbl.CleanName=CleanUp(tbl.Name); + tbl.ClassName=Inflector.MakeSingular(tbl.CleanName); + tbl.QueryableName=Inflector.MakePlural(tbl.ClassName); + + //set the PK for the columns + var pkColumn=tbl.Columns.SingleOrDefault(x=>x.Name.ToLower().Trim()==tbl.PrimaryKey.ToLower().Trim()); + if(pkColumn!=null) + pkColumn.IsPK=true; + + tbl.FKTables=LoadFKTables(tbl.Name); + + result.Add(tbl); + } + } + + foreach(Table tbl in result){ + //loop the FK tables and see if there's a match for our FK columns + foreach(Column col in tbl.Columns){ + col.IsForeignKey=tbl.FKTables.Any( + x=>x.ThisColumn.Equals(col.Name,StringComparison.InvariantCultureIgnoreCase) + ); + } + } + return result; +} + +List LoadColumns(Table tbl){ + var result=new List(); + var cmd=GetCommand(COLUMN_SQL); + cmd.Parameters.AddWithValue("@tableName",tbl.Name); + + using(IDataReader rdr=cmd.ExecuteReader(CommandBehavior.CloseConnection)){ + while(rdr.Read()){ + Column col=new Column(); + col.Name=rdr["ColumnName"].ToString(); + col.CleanName=CleanUp(col.Name); + col.DataType=rdr["DataType"].ToString(); + col.SysType=GetSysType(col.DataType); + col.DbType=GetDbType(col.DataType); + col.AutoIncrement=rdr["IsIdentity"].ToString()=="1"; + col.IsNullable=rdr["IsNullable"].ToString()=="YES"; + int.TryParse(rdr["MaxLength"].ToString(),out col.MaxLength); + + result.Add(col); + } + + } + + return result; +} + +List LoadFKTables(string tableName){ + + //this is a "bi-directional" scheme + //which pulls both 1-many and many-1 + + var result=new List(); + var cmd=GetCommand(FKSql); + cmd.Parameters.AddWithValue("@tableName",tableName); + using(IDataReader rdr=cmd.ExecuteReader(CommandBehavior.CloseConnection)){ + while(rdr.Read()){ + FKTable fk=new FKTable(); + string thisTable=rdr["ThisTable"].ToString(); + + if(tableName.ToLower()==thisTable.ToLower()){ + fk.ThisTable=rdr["ThisTable"].ToString(); + fk.ThisColumn=rdr["ThisColumn"].ToString(); + fk.OtherTable=rdr["OtherTable"].ToString(); + fk.OtherColumn=rdr["OtherColumn"].ToString(); + + }else{ + fk.ThisTable=rdr["OtherTable"].ToString(); + fk.ThisColumn=rdr["OtherColumn"].ToString(); + fk.OtherTable=rdr["ThisTable"].ToString(); + fk.OtherColumn=rdr["ThisColumn"].ToString(); + + } + + fk.OtherClass=Inflector.MakeSingular(CleanUp(fk.OtherTable)); + fk.OtherQueryable=Inflector.MakePlural(fk.OtherClass); + + result.Add(fk); + } + } + return result; + +} + +string GetPK(string table){ + + string pk=""; + DataTable pkTable=new DataTable(); + string sql=@"SELECT KCU.COLUMN_NAME + FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU + JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC + ON KCU.CONSTRAINT_NAME=TC.CONSTRAINT_NAME + WHERE TC.CONSTRAINT_TYPE='PRIMARY KEY' + AND KCU.TABLE_NAME=@tableName"; + + var cmd=GetCommand(sql); + cmd.Parameters.AddWithValue("@tableName",table); + var result=cmd.ExecuteScalar(); + cmd.Dispose(); + if(result!=null) + pk=result.ToString(); + + return pk; +} + +string GetSysType(string sqlType){ + string sysType="string"; + switch (sqlType) { + case "bigint": + sysType = "long"; + break; + case "smallint": + sysType= "short"; + break; + case "int": + sysType= "int"; + break; + case "uniqueidentifier": + sysType= "Guid"; + break; + case "smalldatetime": + case "datetime": + sysType= "DateTime"; + break; + case "float": + sysType="double"; + break; + case "real": + case "numeric": + case "smallmoney": + case "decimal": + case "money": + sysType= "decimal"; + break; + case "tinyint": + case "bit": + sysType= "bool"; + break; + case "image": + case "binary": + case "varbinary": + sysType= "byte[]"; + break; + } + return sysType; +} +DbType GetDbType(string sqlType){ + switch(sqlType) + { + case "varchar": + return DbType.AnsiString; + case "nvarchar": + return DbType.String; + case "int": + return DbType.Int32; + case "uniqueidentifier": + return DbType.Guid; + case "datetime": + return DbType.DateTime; + case "bigint": + return DbType.Int64; + case "binary": + return DbType.Binary; + case "bit": + return DbType.Boolean; + case "char": + return DbType.AnsiStringFixedLength; + case "decimal": + return DbType.Decimal; + case "float": + return DbType.Double; + case "image": + return DbType.Binary; + case "money": + return DbType.Currency; + case "nchar": + return DbType.String; + case "ntext": + return DbType.String; + case "numeric": + return DbType.Decimal; + case "real": + return DbType.Single; + case "smalldatetime": + return DbType.DateTime; + case "smallint": + return DbType.Int16; + case "smallmoney": + return DbType.Currency; + case "sql_variant": + return DbType.String; + case "sysname": + return DbType.String; + case "text": + return DbType.AnsiString; + case "timestamp": + return DbType.Binary; + case "tinyint": + return DbType.Byte; + case "varbinary": + return DbType.Binary; + default: + return DbType.AnsiString; + } + +} + +#> \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/Generated/Settings.ttinclude b/SubSonic.Tests/BugReports/Generated/Settings.ttinclude new file mode 100644 index 0000000..9aaf941 --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/Settings.ttinclude @@ -0,0 +1,548 @@ +<#@ template language="C#v3.5" debug="True" hostspecific="True" #> +<#@ assembly name="EnvDTE" #> +<#@ assembly name="System.Core.dll" #> +<#@ assembly name="System.Data" #> +<#@ assembly name="System.Xml" #> +<#@ assembly name="System.Configuration" #> +<#@ import namespace="System.Collections.Generic" #> +<#@ import namespace="System.Data" #> +<#@ import namespace="System.Data.SqlClient" #> +<#@ import namespace="System.Data.Common" #> +<#@ import namespace="System.Diagnostics" #> +<#@ import namespace="System.Globalization" #> +<#@ import namespace="System.IO" #> +<#@ import namespace="System.Linq" #> +<#@ import namespace="System.Text" #> +<#@ import namespace="System.Text.RegularExpressions" #> +<#@ import namespace="System.Configuration" #> + +<#+ + + const string Namespace = "SouthWind"; + const string ConnectionStringName = "Northwind"; + + //This is the name of your database and is used in naming + //the repository. By default we set it to the connection string name + const string DatabaseName = "Northwind"; + + //this is a list of tables you don't want generated + string[] ExcludeTables = new string[]{ + "sysdiagrams", + "BuildVersion", + }; + + string CleanUp(string tableName){ + string result=tableName; + + //strip blanks + result=result.Replace(" ",""); + + //put your logic here... + + return result; + } + string CheckNullable(Column col){ + string result=""; + if(col.IsNullable && col.SysType !="byte[]" && col.SysType !="string") + result="?"; + return result; + } + string GetConnectionString(string connectionStringName){ + var _CurrentProject = GetCurrentProject(); + + string result=""; + ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(); + configFile.ExeConfigFilename = GetConfigPath(); + + if (string.IsNullOrEmpty(configFile.ExeConfigFilename)) + throw new ArgumentNullException("The project does not contain App.config or Web.config file."); + + + var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None); + var connSection=config.ConnectionStrings; + + //if the connectionString is empty - which is the defauls + //look for count-1 - this is the last connection string + //and takes into account AppServices and LocalSqlServer + if(string.IsNullOrEmpty(connectionStringName)){ + if(connSection.ConnectionStrings.Count>1){ + result=connSection.ConnectionStrings[connSection.ConnectionStrings.Count-1].ConnectionString; + } + }else{ + try{ + result=connSection.ConnectionStrings[connectionStringName].ConnectionString; + }catch{ + result="There is no connection string name called '"+connectionStringName+"'"; + } + } + + return result; + } + + string _connectionString=""; + public string ConnectionString{ + get { + if(String.IsNullOrEmpty(_connectionString)){ + + _connectionString=GetConnectionString(ConnectionStringName); + + } + + if(_connectionString.Contains("|DataDirectory|")){ + //have to replace it + string dataFilePath=GetDataDirectory(); + _connectionString=_connectionString.Replace("|DataDirectory|",dataFilePath); + } + + return _connectionString; + } + } + + public EnvDTE.Project GetCurrentProject() { + + IServiceProvider _ServiceProvider = (IServiceProvider)Host; + if (_ServiceProvider == null) + throw new Exception("Host property returned unexpected value (null)"); + + EnvDTE.DTE dte = (EnvDTE.DTE)_ServiceProvider.GetService(typeof(EnvDTE.DTE)); + if (dte == null) + throw new Exception("Unable to retrieve EnvDTE.DTE"); + + Array activeSolutionProjects = (Array)dte.ActiveSolutionProjects; + if (activeSolutionProjects == null) + throw new Exception("DTE.ActiveSolutionProjects returned null"); + + EnvDTE.Project dteProject = (EnvDTE.Project)activeSolutionProjects.GetValue(0); + if (dteProject == null) + throw new Exception("DTE.ActiveSolutionProjects[0] returned null"); + + return dteProject; + + } + + private string GetProjectPath() + { + EnvDTE.Project project = GetCurrentProject(); + System.IO.FileInfo info = new System.IO.FileInfo(project.FullName); + return info.Directory.FullName; + } + + private string GetConfigPath() + { + EnvDTE.Project project = GetCurrentProject(); + foreach (EnvDTE.ProjectItem item in project.ProjectItems) + { + // if it is the app.config file, then open it up + if (item.Name.Equals("App.config",StringComparison.InvariantCultureIgnoreCase) || item.Name.Equals("Web.config",StringComparison.InvariantCultureIgnoreCase)) + return GetProjectPath() + "\\" + item.Name; + } + return String.Empty; + } + + public string GetDataDirectory(){ + EnvDTE.Project project=GetCurrentProject(); + return System.IO.Path.GetDirectoryName(project.FileName)+"\\App_Data\\"; + } + + public class Table{ + + public List Columns; + public List FKTables; + public string Name; + public string CleanName; + public string ClassName; + public string PrimaryKey; + public string Schema; + public string QueryableName; + + public bool HasLogicalDelete(){ + return this.Columns.Any(x=>x.Name.ToLower()=="deleted" || x.Name.ToLower()=="isdeleted"); + } + public Column DeleteColumn{ + get{ + Column result=null; + if(this.Columns.Any(x=>x.Name.ToLower()=="deleted")) + result=this.Columns.Single(x=>x.Name.ToLower()=="deleted"); + if(this.Columns.Any(x=>x.Name.ToLower()=="isdeleted")) + result=this.Columns.Single(x=>x.Name.ToLower()=="isdeleted"); + return result; + } + } + public Column PK{ + get{ + return this.Columns.SingleOrDefault(x=>x.IsPK) ?? this.Columns[0]; + } + } + public Column Descriptor{ + get{ + if(this.Columns.Count==1){ + return this.Columns[0]; + }else{ + //get the first string column + Column result=null; + result=this.Columns.FirstOrDefault(x=>x.SysType.ToLower().Trim()=="string"); + if(result==null) + result=this.Columns[1]; + return result; + } + } + } + } + + public class Column{ + public string Name; + public string CleanName; + public string SysType; + public string DataType; + public DbType DbType; + public bool AutoIncrement; + public bool IsPK; + public int MaxLength; + public bool IsNullable; + public bool IsForeignKey; + } + public class FKTable{ + public string ThisTable; + public string ThisColumn; + public string OtherTable; + public string OtherColumn; + public string OtherClass; + public string OtherQueryable; + } + + public class SP{ + public string Name; + public string CleanName; + public string ClassName; + public List Parameters; + public SP(){ + Parameters=new List(); + } + public string ArgList{ + get{ + StringBuilder sb=new StringBuilder(); + int loopCount=1; + foreach(var par in Parameters){ + sb.AppendFormat("{0} {1}", par.SysType,par.CleanName); + if(loopCount + /// Summary for the Inflector class + /// + public static class Inflector { + private static readonly List _plurals = new List(); + private static readonly List _singulars = new List(); + private static readonly List _uncountables = new List(); + + /// + /// Initializes the class. + /// + static Inflector() { + AddPluralRule("$", "s"); + AddPluralRule("s$", "s"); + AddPluralRule("(ax|test)is$", "$1es"); + AddPluralRule("(octop|vir)us$", "$1i"); + AddPluralRule("(alias|status)$", "$1es"); + AddPluralRule("(bu)s$", "$1ses"); + AddPluralRule("(buffal|tomat)o$", "$1oes"); + AddPluralRule("([ti])um$", "$1a"); + AddPluralRule("sis$", "ses"); + AddPluralRule("(?:([^f])fe|([lr])f)$", "$1$2ves"); + AddPluralRule("(hive)$", "$1s"); + AddPluralRule("([^aeiouy]|qu)y$", "$1ies"); + AddPluralRule("(x|ch|ss|sh)$", "$1es"); + AddPluralRule("(matr|vert|ind)ix|ex$", "$1ices"); + AddPluralRule("([m|l])ouse$", "$1ice"); + AddPluralRule("^(ox)$", "$1en"); + AddPluralRule("(quiz)$", "$1zes"); + + AddSingularRule("s$", String.Empty); + AddSingularRule("ss$", "ss"); + AddSingularRule("(n)ews$", "$1ews"); + AddSingularRule("([ti])a$", "$1um"); + AddSingularRule("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis"); + AddSingularRule("(^analy)ses$", "$1sis"); + AddSingularRule("([^f])ves$", "$1fe"); + AddSingularRule("(hive)s$", "$1"); + AddSingularRule("(tive)s$", "$1"); + AddSingularRule("([lr])ves$", "$1f"); + AddSingularRule("([^aeiouy]|qu)ies$", "$1y"); + AddSingularRule("(s)eries$", "$1eries"); + AddSingularRule("(m)ovies$", "$1ovie"); + AddSingularRule("(x|ch|ss|sh)es$", "$1"); + AddSingularRule("([m|l])ice$", "$1ouse"); + AddSingularRule("(bus)es$", "$1"); + AddSingularRule("(o)es$", "$1"); + AddSingularRule("(shoe)s$", "$1"); + AddSingularRule("(cris|ax|test)es$", "$1is"); + AddSingularRule("(octop|vir)i$", "$1us"); + AddSingularRule("(alias|status)$", "$1"); + AddSingularRule("(alias|status)es$", "$1"); + AddSingularRule("^(ox)en", "$1"); + AddSingularRule("(vert|ind)ices$", "$1ex"); + AddSingularRule("(matr)ices$", "$1ix"); + AddSingularRule("(quiz)zes$", "$1"); + + AddIrregularRule("person", "people"); + AddIrregularRule("man", "men"); + AddIrregularRule("child", "children"); + AddIrregularRule("sex", "sexes"); + AddIrregularRule("tax", "taxes"); + AddIrregularRule("move", "moves"); + + AddUnknownCountRule("equipment"); + AddUnknownCountRule("information"); + AddUnknownCountRule("rice"); + AddUnknownCountRule("money"); + AddUnknownCountRule("species"); + AddUnknownCountRule("series"); + AddUnknownCountRule("fish"); + AddUnknownCountRule("sheep"); + } + + /// + /// Adds the irregular rule. + /// + /// The singular. + /// The plural. + private static void AddIrregularRule(string singular, string plural) { + AddPluralRule(String.Concat("(", singular[0], ")", singular.Substring(1), "$"), String.Concat("$1", plural.Substring(1))); + AddSingularRule(String.Concat("(", plural[0], ")", plural.Substring(1), "$"), String.Concat("$1", singular.Substring(1))); + } + + /// + /// Adds the unknown count rule. + /// + /// The word. + private static void AddUnknownCountRule(string word) { + _uncountables.Add(word.ToLower()); + } + + /// + /// Adds the plural rule. + /// + /// The rule. + /// The replacement. + private static void AddPluralRule(string rule, string replacement) { + _plurals.Add(new InflectorRule(rule, replacement)); + } + + /// + /// Adds the singular rule. + /// + /// The rule. + /// The replacement. + private static void AddSingularRule(string rule, string replacement) { + _singulars.Add(new InflectorRule(rule, replacement)); + } + + /// + /// Makes the plural. + /// + /// The word. + /// + public static string MakePlural(string word) { + return ApplyRules(_plurals, word); + } + + /// + /// Makes the singular. + /// + /// The word. + /// + public static string MakeSingular(string word) { + return ApplyRules(_singulars, word); + } + + /// + /// Applies the rules. + /// + /// The rules. + /// The word. + /// + private static string ApplyRules(IList rules, string word) { + string result = word; + if (!_uncountables.Contains(word.ToLower())) { + for (int i = rules.Count - 1; i >= 0; i--) { + string currentPass = rules[i].Apply(word); + if (currentPass != null) { + result = currentPass; + break; + } + } + } + return result; + } + + /// + /// Converts the string to title case. + /// + /// The word. + /// + public static string ToTitleCase(string word) { + return Regex.Replace(ToHumanCase(AddUnderscores(word)), @"\b([a-z])", + delegate(Match match) { return match.Captures[0].Value.ToUpper(); }); + } + + /// + /// Converts the string to human case. + /// + /// The lowercase and underscored word. + /// + public static string ToHumanCase(string lowercaseAndUnderscoredWord) { + return MakeInitialCaps(Regex.Replace(lowercaseAndUnderscoredWord, @"_", " ")); + } + + + /// + /// Adds the underscores. + /// + /// The pascal cased word. + /// + public static string AddUnderscores(string pascalCasedWord) { + return Regex.Replace(Regex.Replace(Regex.Replace(pascalCasedWord, @"([A-Z]+)([A-Z][a-z])", "$1_$2"), @"([a-z\d])([A-Z])", "$1_$2"), @"[-\s]", "_").ToLower(); + } + + /// + /// Makes the initial caps. + /// + /// The word. + /// + public static string MakeInitialCaps(string word) { + return String.Concat(word.Substring(0, 1).ToUpper(), word.Substring(1).ToLower()); + } + + /// + /// Makes the initial lower case. + /// + /// The word. + /// + public static string MakeInitialLowerCase(string word) { + return String.Concat(word.Substring(0, 1).ToLower(), word.Substring(1)); + } + + + /// + /// Determine whether the passed string is numeric, by attempting to parse it to a double + /// + /// The string to evaluated for numeric conversion + /// + /// true if the string can be converted to a number; otherwise, false. + /// + public static bool IsStringNumeric(string str) { + double result; + return (double.TryParse(str, NumberStyles.Float, NumberFormatInfo.CurrentInfo, out result)); + } + + /// + /// Adds the ordinal suffix. + /// + /// The number. + /// + public static string AddOrdinalSuffix(string number) { + if (IsStringNumeric(number)) { + int n = int.Parse(number); + int nMod100 = n % 100; + + if (nMod100 >= 11 && nMod100 <= 13) + return String.Concat(number, "th"); + + switch (n % 10) { + case 1: + return String.Concat(number, "st"); + case 2: + return String.Concat(number, "nd"); + case 3: + return String.Concat(number, "rd"); + default: + return String.Concat(number, "th"); + } + } + return number; + } + + /// + /// Converts the underscores to dashes. + /// + /// The underscored word. + /// + public static string ConvertUnderscoresToDashes(string underscoredWord) { + return underscoredWord.Replace('_', '-'); + } + + + #region Nested type: InflectorRule + + /// + /// Summary for the InflectorRule class + /// + private class InflectorRule { + /// + /// + /// + public readonly Regex regex; + + /// + /// + /// + public readonly string replacement; + + /// + /// Initializes a new instance of the class. + /// + /// The regex pattern. + /// The replacement text. + public InflectorRule(string regexPattern, string replacementText) { + regex = new Regex(regexPattern, RegexOptions.IgnoreCase); + replacement = replacementText; + } + + /// + /// Applies the specified word. + /// + /// The word. + /// + public string Apply(string word) { + if (!regex.IsMatch(word)) + return null; + + string replace = regex.Replace(word, replacement); + if (word == word.ToUpper()) + replace = replace.ToUpper(); + + return replace; + } + } + + #endregion + } + +#> \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/Generated/StoredProcedures.cs b/SubSonic.Tests/BugReports/Generated/StoredProcedures.cs new file mode 100644 index 0000000..8a7e2ce --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/StoredProcedures.cs @@ -0,0 +1,55 @@ + + + + +using System; +using SubSonic; +using SubSonic.Schema; +using SubSonic.DataProviders; +using System.Data; + +namespace SouthWind{ + public partial class NorthwindDB{ + + public StoredProcedure CustOrderHist(string CustomerID){ + StoredProcedure sp=new StoredProcedure("CustOrderHist",this.Provider); + sp.Command.AddParameter("CustomerID",CustomerID,DbType.String); + return sp; + } + public StoredProcedure CustOrdersDetail(int OrderID){ + StoredProcedure sp=new StoredProcedure("CustOrdersDetail",this.Provider); + sp.Command.AddParameter("OrderID",OrderID,DbType.Int32); + return sp; + } + public StoredProcedure CustOrdersOrders(string CustomerID){ + StoredProcedure sp=new StoredProcedure("CustOrdersOrders",this.Provider); + sp.Command.AddParameter("CustomerID",CustomerID,DbType.String); + return sp; + } + public StoredProcedure EmployeeSalesbyCountry(DateTime Beginning_Date,DateTime Ending_Date){ + StoredProcedure sp=new StoredProcedure("Employee Sales by Country",this.Provider); + sp.Command.AddParameter("Beginning_Date",Beginning_Date,DbType.DateTime); + sp.Command.AddParameter("Ending_Date",Ending_Date,DbType.DateTime); + return sp; + } + public StoredProcedure SalesbyYear(DateTime Beginning_Date,DateTime Ending_Date){ + StoredProcedure sp=new StoredProcedure("Sales by Year",this.Provider); + sp.Command.AddParameter("Beginning_Date",Beginning_Date,DbType.DateTime); + sp.Command.AddParameter("Ending_Date",Ending_Date,DbType.DateTime); + return sp; + } + public StoredProcedure SalesByCategory(string CategoryName,string OrdYear){ + StoredProcedure sp=new StoredProcedure("SalesByCategory",this.Provider); + sp.Command.AddParameter("CategoryName",CategoryName,DbType.String); + sp.Command.AddParameter("OrdYear",OrdYear,DbType.String); + return sp; + } + public StoredProcedure TenMostExpensiveProducts(){ + StoredProcedure sp=new StoredProcedure("Ten Most Expensive Products",this.Provider); + return sp; + } + + } + +} + \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/Generated/StoredProcedures.tt b/SubSonic.Tests/BugReports/Generated/StoredProcedures.tt new file mode 100644 index 0000000..2152864 --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/StoredProcedures.tt @@ -0,0 +1,30 @@ +<#@ template language="C#v3.5" debug="False" hostspecific="True" #> +<#@ output extension=".cs" #> +<#@ include file="SQLServer.ttinclude" #> +<# + var sps = GetSPs(); + if(sps.Count>0){ +#> +using System; +using SubSonic; +using SubSonic.Schema; +using SubSonic.DataProviders; +using System.Data; + +namespace <#=Namespace#>{ + public partial class <#=DatabaseName#>DB{ + +<# foreach(var sp in sps){#> + public StoredProcedure <#=sp.CleanName#>(<#=sp.ArgList#>){ + StoredProcedure sp=new StoredProcedure("<#=sp.Name#>",this.Provider); +<# foreach(var par in sp.Parameters){#> + sp.Command.AddParameter("<#=par.Name#>",<#=par.CleanName#>,DbType.<#=par.DbType#>); +<# }#> + return sp; + } +<# }#> + + } + +} +<# }#> \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/Generated/Structs.cs b/SubSonic.Tests/BugReports/Generated/Structs.cs new file mode 100644 index 0000000..7282d68 --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/Structs.cs @@ -0,0 +1,1793 @@ + + + +using System; +using SubSonic.Schema; +using System.Collections.Generic; +using SubSonic.DataProviders; +using System.Data; + +namespace SouthWind { + + /// + /// Table: Customers + /// Primary Key: CustomerID + /// + + public class CustomersTable: DatabaseTable { + + public CustomersTable(IDataProvider provider):base("Customers",provider){ + ClassName = "Customer"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("CustomerID", this) + { + IsPrimaryKey = true, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("CompanyName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ContactName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ContactTitle", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Address", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("City", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Region", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("PostalCode", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Country", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Phone", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Fax", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn CustomerID{ + get{ + return this.GetColumn("CustomerID"); + } + } + + public IColumn CompanyName{ + get{ + return this.GetColumn("CompanyName"); + } + } + + public IColumn ContactName{ + get{ + return this.GetColumn("ContactName"); + } + } + + public IColumn ContactTitle{ + get{ + return this.GetColumn("ContactTitle"); + } + } + + public IColumn Address{ + get{ + return this.GetColumn("Address"); + } + } + + public IColumn City{ + get{ + return this.GetColumn("City"); + } + } + + public IColumn Region{ + get{ + return this.GetColumn("Region"); + } + } + + public IColumn PostalCode{ + get{ + return this.GetColumn("PostalCode"); + } + } + + public IColumn Country{ + get{ + return this.GetColumn("Country"); + } + } + + public IColumn Phone{ + get{ + return this.GetColumn("Phone"); + } + } + + public IColumn Fax{ + get{ + return this.GetColumn("Fax"); + } + } + + + } + + /// + /// Table: Shippers + /// Primary Key: ShipperID + /// + + public class ShippersTable: DatabaseTable { + + public ShippersTable(IDataProvider provider):base("Shippers",provider){ + ClassName = "Shipper"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("ShipperID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = true, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("CompanyName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Phone", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn ShipperID{ + get{ + return this.GetColumn("ShipperID"); + } + } + + public IColumn CompanyName{ + get{ + return this.GetColumn("CompanyName"); + } + } + + public IColumn Phone{ + get{ + return this.GetColumn("Phone"); + } + } + + + } + + /// + /// Table: Suppliers + /// Primary Key: SupplierID + /// + + public class SuppliersTable: DatabaseTable { + + public SuppliersTable(IDataProvider provider):base("Suppliers",provider){ + ClassName = "Supplier"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("SupplierID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = true, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("CompanyName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ContactName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ContactTitle", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Address", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("City", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Region", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("PostalCode", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Country", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Phone", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Fax", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("HomePage", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn SupplierID{ + get{ + return this.GetColumn("SupplierID"); + } + } + + public IColumn CompanyName{ + get{ + return this.GetColumn("CompanyName"); + } + } + + public IColumn ContactName{ + get{ + return this.GetColumn("ContactName"); + } + } + + public IColumn ContactTitle{ + get{ + return this.GetColumn("ContactTitle"); + } + } + + public IColumn Address{ + get{ + return this.GetColumn("Address"); + } + } + + public IColumn City{ + get{ + return this.GetColumn("City"); + } + } + + public IColumn Region{ + get{ + return this.GetColumn("Region"); + } + } + + public IColumn PostalCode{ + get{ + return this.GetColumn("PostalCode"); + } + } + + public IColumn Country{ + get{ + return this.GetColumn("Country"); + } + } + + public IColumn Phone{ + get{ + return this.GetColumn("Phone"); + } + } + + public IColumn Fax{ + get{ + return this.GetColumn("Fax"); + } + } + + public IColumn HomePage{ + get{ + return this.GetColumn("HomePage"); + } + } + + + } + + /// + /// Table: Order Details + /// Primary Key: OrderID + /// + + public class OrderDetailsTable: DatabaseTable { + + public OrderDetailsTable(IDataProvider provider):base("Order Details",provider){ + ClassName = "OrderDetail"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("OrderID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("ProductID", this) + { + IsPrimaryKey = false, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("UnitPrice", this) + { + IsPrimaryKey = false, + DataType = DbType.Currency, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Quantity", this) + { + IsPrimaryKey = false, + DataType = DbType.Int16, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Discount", this) + { + IsPrimaryKey = false, + DataType = DbType.Single, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn OrderID{ + get{ + return this.GetColumn("OrderID"); + } + } + + public IColumn ProductID{ + get{ + return this.GetColumn("ProductID"); + } + } + + public IColumn UnitPrice{ + get{ + return this.GetColumn("UnitPrice"); + } + } + + public IColumn Quantity{ + get{ + return this.GetColumn("Quantity"); + } + } + + public IColumn Discount{ + get{ + return this.GetColumn("Discount"); + } + } + + + } + + /// + /// Table: CustomerCustomerDemo + /// Primary Key: CustomerID + /// + + public class CustomerCustomerDemoTable: DatabaseTable { + + public CustomerCustomerDemoTable(IDataProvider provider):base("CustomerCustomerDemo",provider){ + ClassName = "CustomerCustomerDemo"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("CustomerID", this) + { + IsPrimaryKey = true, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("CustomerTypeID", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + + + } + + public IColumn CustomerID{ + get{ + return this.GetColumn("CustomerID"); + } + } + + public IColumn CustomerTypeID{ + get{ + return this.GetColumn("CustomerTypeID"); + } + } + + + } + + /// + /// Table: CustomerDemographics + /// Primary Key: CustomerTypeID + /// + + public class CustomerDemographicsTable: DatabaseTable { + + public CustomerDemographicsTable(IDataProvider provider):base("CustomerDemographics",provider){ + ClassName = "CustomerDemographic"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("CustomerTypeID", this) + { + IsPrimaryKey = true, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("CustomerDesc", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn CustomerTypeID{ + get{ + return this.GetColumn("CustomerTypeID"); + } + } + + public IColumn CustomerDesc{ + get{ + return this.GetColumn("CustomerDesc"); + } + } + + + } + + /// + /// Table: Region + /// Primary Key: RegionID + /// + + public class RegionTable: DatabaseTable { + + public RegionTable(IDataProvider provider):base("Region",provider){ + ClassName = "Region"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("RegionID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("RegionDescription", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn RegionID{ + get{ + return this.GetColumn("RegionID"); + } + } + + public IColumn RegionDescription{ + get{ + return this.GetColumn("RegionDescription"); + } + } + + + } + + /// + /// Table: Territories + /// Primary Key: TerritoryID + /// + + public class TerritoriesTable: DatabaseTable { + + public TerritoriesTable(IDataProvider provider):base("Territories",provider){ + ClassName = "Territory"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("TerritoryID", this) + { + IsPrimaryKey = true, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("TerritoryDescription", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("RegionID", this) + { + IsPrimaryKey = false, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + + + } + + public IColumn TerritoryID{ + get{ + return this.GetColumn("TerritoryID"); + } + } + + public IColumn TerritoryDescription{ + get{ + return this.GetColumn("TerritoryDescription"); + } + } + + public IColumn RegionID{ + get{ + return this.GetColumn("RegionID"); + } + } + + + } + + /// + /// Table: EmployeeTerritories + /// Primary Key: EmployeeID + /// + + public class EmployeeTerritoriesTable: DatabaseTable { + + public EmployeeTerritoriesTable(IDataProvider provider):base("EmployeeTerritories",provider){ + ClassName = "EmployeeTerritory"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("EmployeeID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("TerritoryID", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + + + } + + public IColumn EmployeeID{ + get{ + return this.GetColumn("EmployeeID"); + } + } + + public IColumn TerritoryID{ + get{ + return this.GetColumn("TerritoryID"); + } + } + + + } + + /// + /// Table: Orders + /// Primary Key: OrderID + /// + + public class OrdersTable: DatabaseTable { + + public OrdersTable(IDataProvider provider):base("Orders",provider){ + ClassName = "Order"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("OrderID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = true, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("CustomerID", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("EmployeeID", this) + { + IsPrimaryKey = false, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("OrderDate", this) + { + IsPrimaryKey = false, + DataType = DbType.DateTime, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("RequiredDate", this) + { + IsPrimaryKey = false, + DataType = DbType.DateTime, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ShippedDate", this) + { + IsPrimaryKey = false, + DataType = DbType.DateTime, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ShipVia", this) + { + IsPrimaryKey = false, + DataType = DbType.Int32, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("Freight", this) + { + IsPrimaryKey = false, + DataType = DbType.Currency, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ShipName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ShipAddress", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ShipCity", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ShipRegion", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ShipPostalCode", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ShipCountry", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn OrderID{ + get{ + return this.GetColumn("OrderID"); + } + } + + public IColumn CustomerID{ + get{ + return this.GetColumn("CustomerID"); + } + } + + public IColumn EmployeeID{ + get{ + return this.GetColumn("EmployeeID"); + } + } + + public IColumn OrderDate{ + get{ + return this.GetColumn("OrderDate"); + } + } + + public IColumn RequiredDate{ + get{ + return this.GetColumn("RequiredDate"); + } + } + + public IColumn ShippedDate{ + get{ + return this.GetColumn("ShippedDate"); + } + } + + public IColumn ShipVia{ + get{ + return this.GetColumn("ShipVia"); + } + } + + public IColumn Freight{ + get{ + return this.GetColumn("Freight"); + } + } + + public IColumn ShipName{ + get{ + return this.GetColumn("ShipName"); + } + } + + public IColumn ShipAddress{ + get{ + return this.GetColumn("ShipAddress"); + } + } + + public IColumn ShipCity{ + get{ + return this.GetColumn("ShipCity"); + } + } + + public IColumn ShipRegion{ + get{ + return this.GetColumn("ShipRegion"); + } + } + + public IColumn ShipPostalCode{ + get{ + return this.GetColumn("ShipPostalCode"); + } + } + + public IColumn ShipCountry{ + get{ + return this.GetColumn("ShipCountry"); + } + } + + + } + + /// + /// Table: SubSonicTests + /// Primary Key: SubSonicTestID + /// + + public class SubSonicTestsTable: DatabaseTable { + + public SubSonicTestsTable(IDataProvider provider):base("SubSonicTests",provider){ + ClassName = "SubSonicTest"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("SubSonicTestID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = true, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Thinger", this) + { + IsPrimaryKey = false, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Name", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("UserName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("CreatedOn", this) + { + IsPrimaryKey = false, + DataType = DbType.DateTime, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Price", this) + { + IsPrimaryKey = false, + DataType = DbType.Decimal, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Discount", this) + { + IsPrimaryKey = false, + DataType = DbType.Double, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Lat", this) + { + IsPrimaryKey = false, + DataType = DbType.Decimal, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Long", this) + { + IsPrimaryKey = false, + DataType = DbType.Decimal, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("SomeFlag", this) + { + IsPrimaryKey = false, + DataType = DbType.Boolean, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("SomeNullableFlag", this) + { + IsPrimaryKey = false, + DataType = DbType.Boolean, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("LongText", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("MediumText", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn SubSonicTestID{ + get{ + return this.GetColumn("SubSonicTestID"); + } + } + + public IColumn Thinger{ + get{ + return this.GetColumn("Thinger"); + } + } + + public IColumn Name{ + get{ + return this.GetColumn("Name"); + } + } + + public IColumn UserName{ + get{ + return this.GetColumn("UserName"); + } + } + + public IColumn CreatedOn{ + get{ + return this.GetColumn("CreatedOn"); + } + } + + public IColumn Price{ + get{ + return this.GetColumn("Price"); + } + } + + public IColumn Discount{ + get{ + return this.GetColumn("Discount"); + } + } + + public IColumn Lat{ + get{ + return this.GetColumn("Lat"); + } + } + + public IColumn Long{ + get{ + return this.GetColumn("Long"); + } + } + + public IColumn SomeFlag{ + get{ + return this.GetColumn("SomeFlag"); + } + } + + public IColumn SomeNullableFlag{ + get{ + return this.GetColumn("SomeNullableFlag"); + } + } + + public IColumn LongText{ + get{ + return this.GetColumn("LongText"); + } + } + + public IColumn MediumText{ + get{ + return this.GetColumn("MediumText"); + } + } + + + } + + /// + /// Table: Products + /// Primary Key: ProductID + /// + + public class ProductsTable: DatabaseTable { + + public ProductsTable(IDataProvider provider):base("Products",provider){ + ClassName = "Product"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("ProductID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = true, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("ProductName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("SupplierID", this) + { + IsPrimaryKey = false, + DataType = DbType.Int32, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("CategoryID", this) + { + IsPrimaryKey = false, + DataType = DbType.Int32, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("QuantityPerUnit", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("UnitPrice", this) + { + IsPrimaryKey = false, + DataType = DbType.Currency, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("UnitsInStock", this) + { + IsPrimaryKey = false, + DataType = DbType.Int16, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("UnitsOnOrder", this) + { + IsPrimaryKey = false, + DataType = DbType.Int64, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ReorderLevel", this) + { + IsPrimaryKey = false, + DataType = DbType.Int16, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Discontinued", this) + { + IsPrimaryKey = false, + DataType = DbType.Boolean, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn ProductID{ + get{ + return this.GetColumn("ProductID"); + } + } + + public IColumn ProductName{ + get{ + return this.GetColumn("ProductName"); + } + } + + public IColumn SupplierID{ + get{ + return this.GetColumn("SupplierID"); + } + } + + public IColumn CategoryID{ + get{ + return this.GetColumn("CategoryID"); + } + } + + public IColumn QuantityPerUnit{ + get{ + return this.GetColumn("QuantityPerUnit"); + } + } + + public IColumn UnitPrice{ + get{ + return this.GetColumn("UnitPrice"); + } + } + + public IColumn UnitsInStock{ + get{ + return this.GetColumn("UnitsInStock"); + } + } + + public IColumn UnitsOnOrder{ + get{ + return this.GetColumn("UnitsOnOrder"); + } + } + + public IColumn ReorderLevel{ + get{ + return this.GetColumn("ReorderLevel"); + } + } + + public IColumn Discontinued{ + get{ + return this.GetColumn("Discontinued"); + } + } + + + } + + /// + /// Table: Employees + /// Primary Key: EmployeeID + /// + + public class EmployeesTable: DatabaseTable { + + public EmployeesTable(IDataProvider provider):base("Employees",provider){ + ClassName = "Employee"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("EmployeeID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = true, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("LastName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("FirstName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Title", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("TitleOfCourtesy", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("BirthDate", this) + { + IsPrimaryKey = false, + DataType = DbType.DateTime, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("HireDate", this) + { + IsPrimaryKey = false, + DataType = DbType.DateTime, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Address", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("City", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Region", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("PostalCode", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Country", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("HomePhone", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Extension", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Photo", this) + { + IsPrimaryKey = false, + DataType = DbType.Binary, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Notes", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("ReportsTo", this) + { + IsPrimaryKey = false, + DataType = DbType.Int32, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("PhotoPath", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn EmployeeID{ + get{ + return this.GetColumn("EmployeeID"); + } + } + + public IColumn LastName{ + get{ + return this.GetColumn("LastName"); + } + } + + public IColumn FirstName{ + get{ + return this.GetColumn("FirstName"); + } + } + + public IColumn Title{ + get{ + return this.GetColumn("Title"); + } + } + + public IColumn TitleOfCourtesy{ + get{ + return this.GetColumn("TitleOfCourtesy"); + } + } + + public IColumn BirthDate{ + get{ + return this.GetColumn("BirthDate"); + } + } + + public IColumn HireDate{ + get{ + return this.GetColumn("HireDate"); + } + } + + public IColumn Address{ + get{ + return this.GetColumn("Address"); + } + } + + public IColumn City{ + get{ + return this.GetColumn("City"); + } + } + + public IColumn Region{ + get{ + return this.GetColumn("Region"); + } + } + + public IColumn PostalCode{ + get{ + return this.GetColumn("PostalCode"); + } + } + + public IColumn Country{ + get{ + return this.GetColumn("Country"); + } + } + + public IColumn HomePhone{ + get{ + return this.GetColumn("HomePhone"); + } + } + + public IColumn Extension{ + get{ + return this.GetColumn("Extension"); + } + } + + public IColumn Photo{ + get{ + return this.GetColumn("Photo"); + } + } + + public IColumn Notes{ + get{ + return this.GetColumn("Notes"); + } + } + + public IColumn ReportsTo{ + get{ + return this.GetColumn("ReportsTo"); + } + } + + public IColumn PhotoPath{ + get{ + return this.GetColumn("PhotoPath"); + } + } + + + } + + /// + /// Table: Categories + /// Primary Key: CategoryID + /// + + public class CategoriesTable: DatabaseTable { + + public CategoriesTable(IDataProvider provider):base("Categories",provider){ + ClassName = "Category"; + SchemaName = "dbo"; + + + Columns.Add(new DatabaseColumn("CategoryID", this) + { + IsPrimaryKey = true, + DataType = DbType.Int32, + IsNullable = false, + AutoIncrement = true, + IsForeignKey = true + }); + + Columns.Add(new DatabaseColumn("CategoryName", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = false, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Description", this) + { + IsPrimaryKey = false, + DataType = DbType.String, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + Columns.Add(new DatabaseColumn("Picture", this) + { + IsPrimaryKey = false, + DataType = DbType.Binary, + IsNullable = true, + AutoIncrement = false, + IsForeignKey = false + }); + + + + } + + public IColumn CategoryID{ + get{ + return this.GetColumn("CategoryID"); + } + } + + public IColumn CategoryName{ + get{ + return this.GetColumn("CategoryName"); + } + } + + public IColumn Description{ + get{ + return this.GetColumn("Description"); + } + } + + public IColumn Picture{ + get{ + return this.GetColumn("Picture"); + } + } + + + } + +} \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/Generated/Structs.tt b/SubSonic.Tests/BugReports/Generated/Structs.tt new file mode 100644 index 0000000..960df58 --- /dev/null +++ b/SubSonic.Tests/BugReports/Generated/Structs.tt @@ -0,0 +1,60 @@ +<#@ template language="C#v3.5" debug="False" hostspecific="True" #> +<#@ output extension=".cs" #> +<#@ include file="SQLServer.ttinclude" #> +<# + var tables = LoadTables(); +#> +using System; +using SubSonic.Schema; +using System.Collections.Generic; +using SubSonic.DataProviders; +using System.Data; + +namespace <#=Namespace#> { + +<# foreach(var tbl in tables){ + if(!ExcludeTables.Contains(tbl.Name)) + { +#> + /// + /// Table: <#=tbl.Name#> + /// Primary Key: <#=tbl.PrimaryKey#> + /// + + public class <#=tbl.CleanName#>Table: DatabaseTable { + + public <#=tbl.CleanName#>Table(IDataProvider provider):base("<#=tbl.Name#>",provider){ + ClassName = "<#=tbl.ClassName#>"; + SchemaName = "<#=tbl.Schema ?? ""#>"; + +<# foreach(var col in tbl.Columns){#> + + Columns.Add(new DatabaseColumn("<#=col.Name#>", this) + { + IsPrimaryKey = <#=col.IsPK.ToString().ToLower()#>, + DataType = DbType.<#=col.DbType.ToString()#>, + IsNullable = <#=col.IsNullable.ToString().ToLower()#>, + AutoIncrement = <#=col.AutoIncrement.ToString().ToLower()#>, + IsForeignKey = <#=col.IsForeignKey.ToString().ToLower()#> + }); +<# }#> + + + } + +<# foreach(var col in tbl.Columns){#> + public IColumn <#=col.CleanName#>{ + get{ + return this.GetColumn("<#=col.Name#>"); + } + } + +<# }#> + } + +<# + } + + } +#> +} \ No newline at end of file diff --git a/SubSonic.Tests/BugReports/LinqGeneratorBugs.cs b/SubSonic.Tests/BugReports/LinqGeneratorBugs.cs new file mode 100644 index 0000000..72effb6 --- /dev/null +++ b/SubSonic.Tests/BugReports/LinqGeneratorBugs.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SubSonic.DataProviders; +using SubSonic.Tests.Linq.TestBases; +using Xunit; + +namespace SubSonic.Tests.BugReports { + public class LinqGeneratorBugs { + + TestDB _db; + public LinqGeneratorBugs() + { + _db = new TestDB(TestConfiguration.MsSql2005TestConnectionString, DbClientTypeName.MsSql); + var setup = new Setup(_db.Provider); + setup.DropTestTables(); + setup.CreateTestTable(); + setup.LoadTestData(); + } + + /// + /// Issue #1 - !=null incorrectly creates "IS NULL" + /// + [Fact] + + public void Linq_With_ProductID_IsNotNull_Should_Return_100() { + var products = from p in _db.Products + where p.ProductID != null + select p; + + Assert.Equal(100, products.Count()); + } + + /// + /// Issue 30 = "==null incorrectly creates "IS NOT NULL" + /// + [Fact] + public void Linq_With_ProductID_IsNull_Should_Return_0() { + var products = from p in _db.Products + where p.ProductID == null + select p; + + Assert.Equal(0, products.Count()); + } + } +} diff --git a/SubSonic.Tests/LINQ/BugReports.cs b/SubSonic.Tests/LINQ/BugReports.cs deleted file mode 100644 index 4d8853b..0000000 --- a/SubSonic.Tests/LINQ/BugReports.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using SubSonic.Tests.Linq.TestBases; -using SubSonic.DataProviders; -using Xunit; - -namespace SubSonic.Tests.LINQ.TestBases { - public class BugReports { - - protected TestDB _db; - - public BugReports() { - _db=new TestDB(ProviderFactory.GetProvider("WestWind")); - } - - [Fact] - public void Not_Equal_Null_Should_Generate_IS_NOT_NULL() { - var qry = from p in _db.Products - where p.ProductID != null - select p; - - Assert.Equal(100, qry.Count()); - } - } -} diff --git a/SubSonic.Tests/SubSonic.Tests.csproj b/SubSonic.Tests/SubSonic.Tests.csproj index a53c81c..034478b 100644 --- a/SubSonic.Tests/SubSonic.Tests.csproj +++ b/SubSonic.Tests/SubSonic.Tests.csproj @@ -58,9 +58,29 @@ + + + True + True + ActiveRecord.tt + + + True + True + Context.tt + + + True + True + StoredProcedures.tt + + + True + True + Structs.tt + - @@ -100,6 +120,24 @@ + + TextTemplatingFileGenerator + ActiveRecord.cs + + + TextTemplatingFileGenerator + Context.cs + + + + + TextTemplatingFileGenerator + StoredProcedures.cs + + + TextTemplatingFileGenerator + Structs.cs +