NBear单表数据插入
【IT168技术文档】
.NET 2.0 , Visual Studio 2005, SQL Server 2005
数据实体接口(对应数据表)
using NBear.Common; namespace Foo.Data { [Table("Article")] public interface IArticle : IEntity { [PrimaryKey] string Id { get; set; } string Title { get; set; } String Content { get; set; } } }
数据实体属性类(NBear 特有)
using NBear.Common; namespace Foo.Data { public class Article { public static PropertyItem Content = new PropertyItem("Content"); public static PropertyItem Id = new PropertyItem("Id"); public static PropertyItem Title = new PropertyItem("Title"); } }
数据访问服务接口
using NBear.Common; using NBear.IoC.Service; using Foo.Data; namespace Foo.Service { public interface IArticleService : IServiceInterface { void CreateArticle(IArticle article); } }
数据访问服务实现类
using NBear.Common; using NBear.Data; using Foo.Data; namespace Foo.Service { public class ArticleService : IArticleService { #region IArticleService 成员 public void CreateArticle(IArticle article) { Gateways.Test.Insert<IArticle>(article); //throw new Exception("The method or operation is not implemented."); } #endregion } }
数据访问路由 Gateways 类(NBear 特有)
using NBear.Data; namespace Foo.Service { /// <summary> /// Init Database access gateways here /// </summary> public abstract class Gateways { private Gateways() { } public static Gateway Test = new Gateway(DatabaseType.SqlServer9, "Data Source=127.0.0.1;Initial Catalog=test;User ID=sa;Password=xxxxxx"); } }
单元测试代码
using NUnit.Framework; using NBear.Common; using Foo.Data; using Foo.Service; namespace Foo.Test { [TestFixture] public class ArticleServiceTest { [Test] public void CreateArticleTest() { ArticleService service = new ArticleService(); IArticle article = EntityFactory<IArticle>.CreateObject(); // 不能设置 id 为 int 自增 // 否则会抛出异常 // 『当 IDENTITY_INSERT 设置为 OFF 时,不能为表 'Article' 中的标识列插入显式值。』 // 所以用 GUID article.Id = Guid.NewGuid().ToString(); article.Title = "abc"; article.Content = "abcdefg123456"; service.CreateArticle(article); } } }
0
相关文章