【发布时间】:2011-10-30 22:57:31
【问题描述】:
目前,我已经非常成功地构建了我的应用程序,如下所示:
数据模型(实体框架 4.1)
使用 Enterprise Library 5.0 验证应用程序块进行验证。
由可重用类库管理的对象上下文。
所以,UI 的代码非常简洁,但我知道我还没有完全做到。
如果我想设置我的项目以便实现 Web 窗体、MVC、WPF 桌面或 Silverlight - 甚至是 Windows Phone 7 - 应用程序,我可能需要采取哪些额外步骤?
这里有一些代码,特意简化,以说明我目前的游戏状态(我省略了代码协定和类库):
(目前是 EF4 模型优先和 ASP .Net Web 表单)
自动生成实体的部分类
namespace MyNamespace.Database
{
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
[HasSelfValidation]
public partial class MyEntity : IMyEntity
{
[SelfValidation]
public void Validate(ValidationResults validationResults)
{
// Custom validation can go here, just add a new ValidationResult
// to validationResults if the rule fails.
if (validationResults != null)
{
validationResults.AddAllResults(
ValidationFactory
.CreateValidator<IMyEntity>()
.Validate(this));
}
}
}
}
验证
namespace MyNamespace.Database
{
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.Contracts;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
[ContractClass(typeof(MyEntityContract))]
public interface IMyEntity
{
int Id
{
get;
set;
}
[Required]
[NotNullValidator]
[StringLengthValidator(0, RangeBoundaryType.Ignore, 50,
RangeBoundaryType.Inclusive,
MessageTemplate = "MyEntity Name must be 50 characters or less.")]
string Name
{
get;
set;
}
void Validate(ValidationResults validationResults);
}
}
数据访问立面
namespace MyNamespace.Facade
{
using System.Collections.Generic;
using System.Linq;
using Common.ObjectContextManagement;
using Database;
public sealed class MyEntityFacade : FacadeBase<MyEntities, MyEntity>
{
public IEnumerable<MyEntity> GetAll()
{
return this.ObjectContext.MyEntitys
.Distinct()
.ToList();
}
}
}
网络应用用户界面
using (new UnitOfWorkScope(false))
{
this.MyEntityList.DataSource = new MyEntityFacade().GetAll();
this.MyEntityList.DataBind();
}
// Or...
using (var scope = new UnitOfWorkScope(false))
{
var myEntityFacade = new MyEntityFacade();
var myEntity = new MyEntity();
PopulateEntity(myEntity);
// Validation errors are automatically presented
// to the user from the Validate method
if (Validate(myEntity))
{
try
{
myEntityFacade.Add(myEntity);
scope.SaveAllChanges();
}
catch (Exception exception)
{
Logging.Write("Error", LoggingLevel.Error, exception.Message);
}
}
}
我离我有多近?
【问题讨论】:
标签: asp.net n-tier-architecture