本文整理汇总了C#中UnitOfWork.Delete方法的典型用法代码示例。如果您正苦于以下问题:C# UnitOfWork.Delete方法的具体用法?C# UnitOfWork.Delete怎么用?C# UnitOfWork.Delete使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UnitOfWork
的用法示例。
在下文中一共展示了UnitOfWork.Delete方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
Console.WriteLine("Creating database/deleting records...");
using(UnitOfWork uow = new UnitOfWork()) {
uow.ConnectionString = Constants.DatabaseConnectionString;
uow.UpdateSchema(typeof(Person));
foreach(Person p in new System.Collections.ArrayList(new XPCollection<Person>(uow))) {
uow.Delete(p);
}
foreach(Product p in new System.Collections.ArrayList(new XPCollection<Product>(uow))) {
uow.Delete(p);
}
uow.CommitChanges();
}
Console.WriteLine("Creating records...");
using(UnitOfWork uow = new UnitOfWork()) {
uow.ConnectionString = Constants.DatabaseConnectionString;
uow.UpdateSchema(typeof(Person));
Person p1 = new Person(uow);
p1.FirstName = "Slava";
p1.LastName = "Donchak";
Person p2 = new Person(uow);
p2.FirstName = "Dan";
p2.LastName = "Ignatov";
Product xaf = new Product(uow);
xaf.Name = "Xaf";
xaf.Manager = p2;
Product xpo = new Product(uow);
xpo.Name = "Xpo";
xpo.Manager = p1;
uow.CommitChanges();
}
Console.WriteLine("Database is recreated.");
Console.ReadLine();
}
示例2: DeleteAllLabel
public static void DeleteAllLabel(UnitOfWork uow)
{
XPCollection<SubPurchOrderReceiveLabel> poReceiveLabels = new XPCollection<SubPurchOrderReceiveLabel>(uow);
uow.Delete(poReceiveLabels);
}
示例3: ExecuteCommand
private void ExecuteCommand(String command, UnitOfWork uow, IExamination examination, object[] param = null)
{
switch (command)
{
case "FileOpened": // передается при открытии файла
{
examination.Status = ExaminationStatus.InProgress;
uow.CommitChanges();
break;
}
case "FileClosed": // при закрытии файла
{
string file = examination.ExaminationFile.RealFileName;
if (String.IsNullOrEmpty(file) == false)
{
FileInfo info = new FileInfo(file);
if ((info.Exists == true && info.Length > 0) || examination.AllowEmptyOrNotExistsFile == true)
{
examination.TimeStop = DateTime.Now;
examination.Status = ExaminationStatus.Completed;
examination.IsBusy = false;
uow.CommitChanges();
break;
}
}
uow.Delete(examination);
uow.CommitChanges();
}
break;
case "FileOpenError":// Ошибка открытия файла
{
examination.IsBusy = false;
uow.CommitChanges();
}
break;
case "FileIsBackToWork":// если файл открыт в приаттаченом процессе
{
if (examination.Status == ExaminationStatus.Registered)
{
examination.Status = ExaminationStatus.InProgress;
uow.CommitChanges();
}
}
break;
case "ProcessStarted":// Процесс запущен
{
examination.IsBusy = true;
//Thread.Sleep(10000);
uow.CommitChanges();
}
break;
case "ProcessExited": // завершился процесс запущенный через плагин
{
if (examination.IsBusy == true)
{ // если при завершении процесса обследование осталось не закрытым
string file = examination.ExaminationFile.RealFileName;
if (String.IsNullOrEmpty(file) == false)
{// проверяем файл
FileInfo info = new FileInfo(file);
if ((info.Exists == true && info.Length > 0) || examination.AllowEmptyOrNotExistsFile == true)
{// если существует не пустой файл или для данного обследования разрешены пустые файлы
examination.TimeStop = DateTime.Now;
examination.Status = ExaminationStatus.Dropped;
examination.IsBusy = false;
uow.CommitChanges();
// помечаем как остановленное и выходим
break;
}
}
// удаляем все что не попало под вышестоящие критерии
uow.Delete(examination);
uow.CommitChanges();
}
}
break;
case "Terminate": // процесс был остановлен пользователем через ProcessKill
{ //обследование прервано если процесс был убит
examination.TimeStop = DateTime.Now;
examination.Status = ExaminationStatus.Dropped;
uow.CommitChanges();
break;
}
case "OpenConclusionFile": // Открыть заключение из EEGStudio
{
try
{
if (((SecuritySystem.CurrentUser as MitsarDataStudio.Module.BusinessObjects.Employee).PermitToConclusion) == true)
{// у пользователя есть права для работы с заключениями
string title = examination.Patient.FullName;
string file = examination.ConclusionFile.RealFileName;
//.........这里部分代码省略.........
示例4: DeleteOutdatedFrame
private static void DeleteOutdatedFrame(Damany.Util.DateTimeRange range, UnitOfWork uow)
{
var cs = string.Format("CaptureTime >= '{0}' And CaptureTime < '{1}'", range.From, range.To);
var c = DevExpress.Data.Filtering.CriteriaOperator.Parse(cs);
var frames = new XPCollection<Damany.PortraitCapturer.DAL.DTO.Frame>(uow, c);
uow.Delete(frames);
}
示例5: DeleteRegion
public bool DeleteRegion(long userId, long regionId)
{
using (var unitOfWork = new UnitOfWork(_connectionString))
{
bool userAuthorised = UserAuthorizedToAccessRegion(unitOfWork, userId, regionId, new[] {RoleType.Admin});
if (!userAuthorised)
throw new UnauthorizedUserException("User does not have access to delete Region: " + regionId);
var regionFromDB = unitOfWork.Context.Regions.FirstOrDefault(x => x.RegionId == regionId);
if (regionFromDB != null &&
UserAuthorizedToAccessSuite(unitOfWork, userId, regionFromDB.SuiteId, new[] {RoleType.Admin}))
{
//TODO: Delete all mappings
unitOfWork.Delete(regionFromDB);
return true;
}
return false;
}
}
示例6: TransferFile
/// <summary>
/// Метод принимает поток из модулей IDynamicModule
/// </summary>
/// <param name="context">Идентификатор обследования связанного с файлом</param>
/// <param name="fileName">Имя файла</param>
/// <param name="dataStream">Файловый поток</param>
/// <param name="initialSize">Размер файла</param>
public void TransferFile(Guid context, String fileName, Stream dataStream, long initialSize)
{
// Получаем объект для работы с данными БД
UnitOfWork uow = new UnitOfWork((this.Application.CreateObjectSpace() as XPObjectSpace).Session.DataLayer);
if (uow == null)
throw new Exception("Error occurred while creating UnitOfWork object.");
// Находим обследование по ИД
IExamination examination = uow.GetObjectByKey<IExamination>(context);
if (examination == null)
{
DevExpress.Persistent.Base.Tracing.Tracer.LogError("TransferFile({0}, {1}, {2}, {3}) Examination [id={0}] is not found in the database",
context, fileName, "dataStream", initialSize);
return;
//throw new Exception("The examination is not found in the database.");
}
if (String.IsNullOrEmpty(fileName) == true || initialSize <= 0)
throw new Exception("Invalid file transfer params.");
//...
//XtraMessageBox.Show(String.Format("TransferFile: {0}, {1}", context, fileName));
Guid owner = (examination as DevExpress.ExpressApp.DC.DCBaseObject).Oid;
CriteriaOperator criteria = uow.ParseCriteria(String.Format("[OwnerId]= '{0}'", owner));
XPClassInfo info = uow.GetClassInfo(typeof(FileSystemStoreObject));
// находим отображаемые имена файлов данного обследования
var ownerFiles = uow.GetObjects(info, criteria, null, int.MaxValue, false, true).Cast<FileSystemStoreObject>().Select(x => x.FileName).ToList<String>();
FileSystemStoreObject fileStoreObject = new FileSystemStoreObject(uow)
{
OwnerId = owner,//((DevExpress.ExpressApp.DC.DCBaseObject)examination).Oid, // ИД владелеца файла
FileName = GetDatabaseFileName(fileName, ownerFiles),// Path.GetFileName(fileName),
};
uow.CommitChanges(); // создаем в базе новый объект FileSystemStoreObject
// пытаемся записать полученный файл
if (FileProcessor.TryToWriteTransferredFile(fileStoreObject.RealFileName, dataStream) == false)//|| new FileInfo(fileStoreObject.RealFileName).Length != initialSize)
{
//XtraMessageBox.Show(String.Format("File transfer error !!!\n {0}, {1}", context, fileName));
uow.Delete(fileStoreObject); // если записать файл не удалось, то удаляем из базы ссылку на файл
}
uow.CommitChanges();
// Обновляем главное окно
//UpdateWindow(context);
OnViewUpdate();
}
示例7: DeleteSuite
public bool DeleteSuite(SuiteModel suiteModel)
{
if (suiteModel == null) return false;
using (var unitOfWork = new UnitOfWork(_connectionString))
{
var userSuitesInDB =
unitOfWork.Context.SuiteUsers.FirstOrDefault(
x => x.UserId == suiteModel.UserId && x.SuiteId == suiteModel.SuiteId);
if (userSuitesInDB == null)
throw new UnauthorizedUserException(
"Invalid SuiteId or User does not have enough privileges to perform this action");
unitOfWork.Delete(userSuitesInDB);
return true;
//TODO: Validate if all mappings etc get deleted too.
}
}
示例8: DeleteEnvironment
public bool DeleteEnvironment(long userId, long environmentId)
{
using (var unitOfWork = new UnitOfWork(_connectionString))
{
bool userAuthorized = UserAuthorizedToAccessEnvironment(unitOfWork, userId, environmentId,
new[] {RoleType.Admin});
if (!userAuthorized)
throw new UnauthorizedUserException("User does not have enough privileges to perform this action");
var environmentFromDB =
unitOfWork.Context.Environments.FirstOrDefault(x => x.EnvironmentId == environmentId);
// check for user again
if (UserAuthorizedToAccessSuite(unitOfWork, userId, environmentFromDB.SuiteId, new[] {RoleType.Admin}))
{
//TODO: Delete all mappings
unitOfWork.Delete(environmentFromDB);
return true;
}
return false;
}
}
示例9: DeleteMapping
public bool DeleteMapping(long userId, long suiteId, long mappingId)
{
var mapToReturn = new List<MappingModel>();
using (var unitOfWork = new UnitOfWork(_connectionString))
{
bool userAuthorised = UserAuthorizedToAccessSuite(unitOfWork, userId, suiteId, new[] {RoleType.Admin});
if (!userAuthorised)
throw new UnauthorizedUserException(
"User does not have access or sufficient privileges for this action to suite: " + suiteId);
var mapping =
unitOfWork.Context.Mappings.FirstOrDefault(x => x.SuiteId == suiteId && x.MappingId == mappingId);
if (mapping == null)
throw new InvalidOperationException("No such mapping exists in the suite");
unitOfWork.Delete(mapping);
}
return true;
}
示例10: DeleteServer
public bool DeleteServer(long userId, long serverId)
{
using (var unitOfWork = new UnitOfWork(_connectionString))
{
bool userAuthorised = UserAuthorizedToAccessServer(unitOfWork, userId, serverId, new[] {RoleType.Admin});
if (!userAuthorised)
throw new UnauthorizedUserException("User does not have access to delete Server: " + serverId);
var ServerFromDB = unitOfWork.Context.Servers.FirstOrDefault(x => x.ServerId == serverId);
if (ServerFromDB != null &&
UserAuthorizedToAccessSuite(unitOfWork, userId, ServerFromDB.SuiteId,
new[] {RoleType.Admin, RoleType.ReadOnly}))
{
//TODO: Delete all mappings
unitOfWork.Delete(ServerFromDB);
return true;
}
return false;
}
}
示例11: DeleteForPeriod
public static void DeleteForPeriod(UnitOfWork uow, int Year, int Month)
{
XPCollection<SubItemMonthly> DeleteRecord = new XPCollection<SubItemMonthly>(uow);
DeleteRecord.Criteria = CriteriaOperator.Parse(string.Format(" Year = {0} AND Month = {1}", Year, Month));
uow.Delete(DeleteRecord);
}
示例12: DeleteWorkday
private void DeleteWorkday(Guid userID, DateTime dateFrom, DateTime dateTo,
string workdaySrcType, string workdayStatus1, string workdayStatus2, params Guid[] listProfileID)
{
using (var context = new VnrHrmDataContext())
{
var unitOfWork = new UnitOfWork(context);
int pageSize = 2000;//tối đa là 2100 parameter
foreach (var listProfileIDBySize in listProfileID.Chunk(pageSize))
{
var workdayQueryable = unitOfWork.CreateQueryable<Att_Workday>(userID, d => d.WorkDate >= dateFrom.Date && d.WorkDate <= dateTo
&& (d.SrcType == null || d.SrcType != workdaySrcType) && (d.Status == null || (d.Status != workdayStatus1 && d.Status != workdayStatus2))
&& (listProfileID.Contains(d.ProfileID) || (d.Hre_Profile.IsDelete.HasValue && d.Hre_Profile.IsDelete.Value)));
var result = unitOfWork.Delete(workdayQueryable);
}
}
}
示例13: SaveRoster
public DataErrorCode SaveRoster()
{
var dataErrorCode = DataErrorCode.Success;
var ListRosterCorrect = GetImportObject();
if (ListRosterCorrect != null && ListRosterCorrect.Count() > 0)
{
using (var context = new VnrHrmDataContext())
{
IUnitOfWork unitOfWork = new UnitOfWork(context);
var listDuplicate = new List<Att_Roster>();
var listRoster = ListRosterCorrect.Select(d =>
new Att_Roster
{
ProfileID = d.ProfileID,
DateStart = d.DateStart,
DateEnd = d.DateEnd,
MonShiftID = d.MonShiftID,
TueShiftID = d.TueShiftID,
WedShiftID = d.WedShiftID,
ThuShiftID = d.ThuShiftID,
FriShiftID = d.FriShiftID,
SatShiftID = d.SatShiftID,
SunShiftID = d.SunShiftID,
Type = RosterType.E_DEFAULT.ToString(),
Status = RosterStatus.E_APPROVED.ToString()
}).ToArray();
if (ImportType == ImportRosterType.OverrideMonth)
{
var listProfileID = listRoster.Select(d => d.ProfileID).Distinct().ToList();
var dateStart = listRoster.Where(d => d.DateStart > SqlDateTime.MinValue.Value).Select(d => d.DateStart.Date).OrderBy(d => d).FirstOrDefault();
var dateEnd = dateStart.AddMonths(1).Date;//Sau này nếu nghiệp vụ thay đổi chỉ xóa những ngày khai báo thì lấy max của cột DateEnd trong danh sách
//Không xóa theo kiểu miền giao DateStart và DateEnd -> có thể sai trường hợp roster dài nhiều tháng
unitOfWork.Delete<Att_Roster>(unitOfWork.CreateQueryable<Att_Roster>(d => d.DateStart >= dateStart
&& d.DateEnd <= dateEnd && listProfileID.Contains(d.ProfileID)));
}
else if (ImportType == ImportRosterType.OverrideHasValue)
{
var listProfileID = listRoster.Select(d => d.ProfileID).Distinct().ToList();
var dateStart = listRoster.Where(d => d.DateStart > SqlDateTime.MinValue.Value).Select(d => d.DateStart.Date).OrderBy(d => d).FirstOrDefault();
var dateEnd = listRoster.Where(d => d.DateEnd > SqlDateTime.MinValue.Value).Select(d => d.DateEnd.Date).OrderBy(d => d).LastOrDefault();
var listOldRoster = unitOfWork.CreateQueryable<Att_Roster>(Guid.Empty, d => d.DateStart <= dateEnd
&& d.DateEnd >= dateStart && listProfileID.Contains(d.ProfileID)).ToList<Att_Roster>();
foreach (var roster in listRoster)
{
DateTime rosterStart = roster.DateStart.Date;
DateTime rosterEnd = roster.DateEnd.Date;
for (DateTime date = rosterStart; date <= rosterEnd; date = date.AddDays(1))
{
var oldRoster = listOldRoster.Where(d => d.DateStart.Date <= date &&
d.DateEnd.Date >= date && d.ProfileID == roster.ProfileID).FirstOrDefault();
if (oldRoster != null)
{
if (date.DayOfWeek == DayOfWeek.Monday && roster.MonShiftID.HasValue)
{
oldRoster.MonShiftID = roster.MonShiftID;
roster.MonShiftID = null;
}
else if (date.DayOfWeek == DayOfWeek.Tuesday && roster.TueShiftID.HasValue)
{
oldRoster.TueShiftID = roster.TueShiftID;
roster.TueShiftID = null;
}
else if (date.DayOfWeek == DayOfWeek.Wednesday && roster.WedShiftID.HasValue)
{
oldRoster.WedShiftID = roster.WedShiftID;
roster.WedShiftID = null;
}
else if (date.DayOfWeek == DayOfWeek.Thursday && roster.ThuShiftID.HasValue)
{
oldRoster.ThuShiftID = roster.ThuShiftID;
roster.ThuShiftID = null;
}
else if (date.DayOfWeek == DayOfWeek.Friday && roster.FriShiftID.HasValue)
{
oldRoster.FriShiftID = roster.FriShiftID;
roster.FriShiftID = null;
}
else if (date.DayOfWeek == DayOfWeek.Saturday && roster.SatShiftID.HasValue)
{
oldRoster.SatShiftID = roster.SatShiftID;
roster.SatShiftID = null;
}
else if (date.DayOfWeek == DayOfWeek.Sunday && roster.SunShiftID.HasValue)
{
oldRoster.SunShiftID = roster.SunShiftID;
roster.SunShiftID = null;
}
}
}
if ((!roster.MonShiftID.HasValue && !roster.TueShiftID.HasValue && !roster.WedShiftID.HasValue
&& !roster.ThuShiftID.HasValue && !roster.FriShiftID.HasValue && !roster.SatShiftID.HasValue
//.........这里部分代码省略.........