本文整理汇总了C#中UnitOfWork类的典型用法代码示例。如果您正苦于以下问题:C# UnitOfWork类的具体用法?C# UnitOfWork怎么用?C# UnitOfWork使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
UnitOfWork类属于命名空间,在下文中一共展示了UnitOfWork类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FrmCrearTipoEmpleado
public FrmCrearTipoEmpleado(TipoEmpleado tipoempleado, XPCollection xpcTipoEmpleado, UnitOfWork uow)
: this()
{
this.TipoEmpleado = tipoempleado;
this.uow = uow;
this.xpcTipoEmpleado = xpcTipoEmpleado;
}
示例2: Application_PostAuthenticateRequest
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported != true) return;
if (Request.Cookies[FormsAuthentication.FormsCookieName] == null) return;
//let us take out the username now
var formsAuthenticationTicket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
if (formsAuthenticationTicket == null) return;
var username = formsAuthenticationTicket.Name;
var roles = String.Empty;
using (IDataContextAsync context = new OIDataContext())
using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
{
IRepositoryAsync<Account> accountRepository = new Repository<Account>(context, unitOfWork);
var user =
accountRepository.Query(u => u.Username == username).Include(r => r.Role).Select().SingleOrDefault();
if (user != null) roles = user.Role.RoleType;
}
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
}
示例3: UpdateDatabaseBeforeUpdateSchema
public override void UpdateDatabaseBeforeUpdateSchema() {
base.UpdateDatabaseBeforeUpdateSchema();
if (CurrentDBVersion > new Version(0, 0, 0, 0) && CurrentDBVersion <= new Version(10, 1, 6)) {
var differenceObjects = new Dictionary<object, string>();
using (var reader = ExecuteReader("select [Oid], [Model] from [ModelDifferenceObject] where [Model] is not null", false)) {
while (reader.Read()) {
differenceObjects.Add(reader[0], reader[1] as string);
}
}
using (var uow = new UnitOfWork(((ObjectSpace)ObjectSpace).Session.DataLayer)) {
foreach (var differenceObject in differenceObjects) {
var modelDifferenceObject = uow.GetObjectByKey<ModelDifferenceObject>(differenceObject.Key);
var serializableDictionary = new SerializableDictionary<string, string>();
var xmlReader = XmlReader.Create(new StringReader(differenceObject.Value), new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Auto });
serializableDictionary.ReadXml(xmlReader);
var aspects = serializableDictionary["aspects"].Split(',').ToList();
var defaultAspect = serializableDictionary["DefaultAspect"];
defaultAspect = GetDefaultAspectFromVersion9(serializableDictionary, aspects, defaultAspect);
if (!string.IsNullOrEmpty(defaultAspect))
modelDifferenceObject.AspectObjects.Add(new AspectObject(uow) { Name = CaptionHelper.DefaultLanguage, Xml = defaultAspect });
foreach (var aspect in aspects.Where(aspect => !string.IsNullOrEmpty(aspect) && !string.IsNullOrEmpty(serializableDictionary[aspect]))) {
modelDifferenceObject.AspectObjects.Add(new AspectObject(uow) { Name = aspect, Xml = serializableDictionary[aspect] });
}
}
uow.CommitChanges();
}
}
}
示例4: ShouldAllowByDefaultRegisterDataSourcesWithSameName
public virtual void ShouldAllowByDefaultRegisterDataSourcesWithSameName()
{
try
{
InternalEnvironment.RegisterDataSource(new DataSource(il => new NullDataSession()));
InternalEnvironment.RegisterDataSource(new DataSource(il => new NullDataSession()));
using (var uow = new UnitOfWork())
{
Awaken(uow);
}
InternalEnvironment.RegisterDataSource(new DataSource("test", IsolationLevel.RepeatableRead, il => new NullDataSession()));
InternalEnvironment.RegisterDataSource(new DataSource("test", il => new NullDataSession()));
using (var uow = new UnitOfWork("test"))
{
Awaken(uow);
}
Assert.That(
() => InternalEnvironment.RegisterDataSource(new DataSource(il => new NullDataSession()), true),
Throws.Exception.With.Message.EqualTo("Data source with name: '' has already been registered."));
Assert.That(
() => InternalEnvironment.RegisterDataSource(new DataSource("test", il => new NullDataSession()), true),
Throws.Exception.With.Message.EqualTo("Data source with name: 'test' has already been registered."));
}
finally
{
InternalEnvironment.UnregisterDataSource();
InternalEnvironment.UnregisterDataSource("test");
}
}
示例5: AddPatientMedication
public ActionResult AddPatientMedication(patientmedication medication)
{
unitOfWork.Repository<patientmedication>().Insert(medication);
unitOfWork.Save();
unitOfWork = new UnitOfWork();
return PartialView("_PatientMedication", unitOfWork.Repository<patientmedication>().Filter(x => x.PatientId == medication.PatientId).Get());
}
示例6: GetByProfileID
public LocationCoreEntity GetByProfileID(string strProfileID)
{
LocationCoreEntity objLocationCoreEntity = new LocationCoreEntity();
try
{
Mugurtham.DTO.Profile.Location objLocation = new Mugurtham.DTO.Profile.Location();
IUnitOfWork objUOW = new UnitOfWork();
using (objUOW as IDisposable)
objLocation = objUOW.RepositoryLocation.GetAll().ToList().Where(p => p.ProfileID.Trim().ToLower() == strProfileID.Trim().ToLower()).FirstOrDefault();
objUOW = null;
if (objLocation != null)
{
using (objLocation as IDisposable)
{
AssignEntityFromDTO(ref objLocation, ref objLocationCoreEntity);
}
}
objLocation = null;
}
catch (Exception objEx)
{
Helpers.LogExceptionInFlatFile(objEx);
}
return objLocationCoreEntity;
}
示例7: Dispose_Then_throw_exception_on_DbContext_get
public void Dispose_Then_throw_exception_on_DbContext_get()
{
var uow1 = new UnitOfWork(_dbContextFactoryMock.Object);
uow1.Dispose();
Assert.Throws<ObjectDisposedException>(() => { var dbContext = uow1.DbContext; });
}
示例8: Create
//Create template
public static int Create(TemplateDTO TemplateDTO)
{
if (TemplateDTO.Title == null || TemplateDTO.Title == "") { return 0; }
try
{
var Template = new Template();
GlobalSettings.LoggedInClientId = TemplateDTO.ClientId;
int PartnerId = ClientService.GetById(TemplateDTO.ClientId).PartnerId;
GlobalSettings.LoggedInPartnerId = PartnerId;
UnitOfWork uow = new UnitOfWork();
Template = Transform.TemplateToDomain(TemplateDTO);
uow.TemplateRepo.Insert(Template);
uow.SaveChanges();
TemplateDTO.Id = Template.Id;
return TemplateDTO.Id;
}
catch (Exception)
{
throw;
}
}
示例9: DeleteUser
TestResult DeleteUser()
{
using (var unitOfWork = new UnitOfWork(new AuthorizationModuleFactory(false)))
{
var UserService = new UserService(unitOfWork);
var testUser = UserService.Get(user => user.Login == "ivan_test++").FirstOrDefault();
UserService.Delete(testUser);
try
{
var result = unitOfWork.Commit();
if (result.Count > 0)
return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, result.First().ErrorMessage);
}
catch (Exception ex)
{
while (ex.InnerException != null)
ex = ex.InnerException;
return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, ex.Message);
}
}
using (var unitOfWork = new UnitOfWork(new AuthorizationModuleFactory(false)))
{
var UserService = new UserService(unitOfWork);
User testUser = UserService.Get(user => user.Login == "ivan_test++").FirstOrDefault();
if (testUser != null)
return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, "Can find deleted user.");
else
return new TestResult(TestResultType.Success, MethodBase.GetCurrentMethod().Name, "User deleted successfully.");
}
}
示例10: updateObjectType
// private void createObjectTypeColumn(XPClassInfo xpClassInfo, UnitOfWork unitOfWork)
// {
// unitOfWork.CreateObjectTypeRecords(xpClassInfo);
// var newObject = xpClassInfo.CreateNewObject(unitOfWork);
// unitOfWork.CommitChanges();
// unitOfWork.Delete(newObject);
// unitOfWork.CommitChanges();
// }
private void updateObjectType(UnitOfWork unitOfWork, XPClassInfo xpClassInfo, XPClassInfo mergedXPClassInfo, IDbCommand command)
{
var propertyName = XPObject.Fields.ObjectType.PropertyName;
command.CommandText = "UPDATE [" + getTableName(mergedXPClassInfo) + "] SET " + propertyName + "=" + unitOfWork.GetObjectType(xpClassInfo).Oid +
" WHERE " + propertyName + " IS NULL OR " + propertyName + "=" +unitOfWork.GetObjectType(mergedXPClassInfo).Oid;
command.ExecuteNonQuery();
}
示例11: FrmCrearTipoNomina
public FrmCrearTipoNomina(TipoNomina tiponomina, XPCollection xpcTipoNomina, UnitOfWork uow)
: this()
{
this.TipoNomina = tiponomina;
this.uow = uow;
this.xpcTipoNomina = xpcTipoNomina;
}
示例12: RefreshUsersList
private void RefreshUsersList()
{
repository = UnitOfWork.CreateInstance();
AllUsers = repository.Users.GetAll().OrderBy(u=>u.UserName).ToList();
UserListViewModel viewModel = new UserListViewModel(AllUsers);
usersbindingSource.DataSource = viewModel.Users;
}
示例13: Setup
public override void Setup(ApplicationModulesManager moduleManager) {
base.Setup(moduleManager);
var businessClassesList = GetAdditionalClasses(moduleManager);
WCTypesInfo.Instance.Register(businessClassesList);
if (Application == null || GetPath() == null)
return;
Application.SettingUp += ApplicationOnSettingUp;
if (FullConnectionString != null) {
var xpoMultiDataStoreProxy = new SqlMultiDataStoreProxy(FullConnectionString, GetReflectionDictionary());
using (var dataLayer = new SimpleDataLayer(xpoMultiDataStoreProxy)) {
using (var session = new Session(dataLayer)) {
using (var unitOfWork = new UnitOfWork(session.DataLayer)) {
RunUpdaters(session);
AddDynamicModules(moduleManager, unitOfWork);
}
}
}
} else {
var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => assembly.ManifestModule.ScopeName.EndsWith(CompileEngine.XpandExtension));
foreach (var assembly1 in assemblies) {
moduleManager.AddModule(assembly1.GetTypes().Where(type => typeof(ModuleBase).IsAssignableFrom(type)).Single());
}
}
Application.SetupComplete += ApplicationOnSetupComplete;
}
示例14: Create
public virtual ActionResult Create(TerminalModel terminal)
{
try
{
using (UnitOfWork unitOfWork = new UnitOfWork())
{
TerminalRepository insertionRepository = new TerminalRepository(unitOfWork.DataContext);
DBTerminal dbTerminal = new DBTerminal
{
Id = terminal.Id,
PhoneNumber = terminal.PhoneNumber,
IsPublic = terminal.IsPublic,
RegionId = terminal.RegionId,
CorrectionFacilityId = terminal.CorrectionFacilityId,
Description = terminal.Description,
IsActive = terminal.IsActive
};
insertionRepository.InsertObject(dbTerminal);
unitOfWork.Commit();
// обновляем идентификатор
terminal.Id = dbTerminal.Id;
}
// сохраняем идентификатор видеотерминала
this.WriteInformation("Видеотерминал с идентификатором \"{0}\" добавлен.", terminal.Id);
return RedirectToAction("Create");
}
catch
{
return View();
}
}
示例15: Create
public async Task<ReturnModel<UserModel>> Create (UserModel userModel)
{
var result = new ReturnModel<UserModel> { Status = true };
using(var session = new UnitOfWork<FoodMenuEntities>())
{
var userRepository = session.GetRepository<IUserRepository>();
if(!(await userRepository.ValidateEmail(userModel.Email,userModel.Id)))
{
result.Error = ("כתובת האמייל כבר בשימוש.");
result.Status = false;
return result;
}
var user = new User();
user.Id = userModel.Id;
user.Email = userModel.Email;
user.Password = userModel.Password;
user.FirstName = userModel.FirstName;
user.LastName = userModel.LastName;
user.BusinessId = userModel.BusinessId;
user.Address = userModel.Address;
user.IsActive = true;
userRepository.Add(user);
await session.SaveChangesAsync();
userModel.Id = user.Id;
userModel.Token = Guid.NewGuid().ToString();
result.Result = userModel;
return result;
}
}