本文整理汇总了C#中IRepository.Where方法的典型用法代码示例。如果您正苦于以下问题:C# IRepository.Where方法的具体用法?C# IRepository.Where怎么用?C# IRepository.Where使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IRepository
的用法示例。
在下文中一共展示了IRepository.Where方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: IndustryModule
public IndustryModule(IPublishStorableCommands publisher, IRepository<Industry> repository)
{
this.RequiresAnyClaim(new[] { RoleType.Admin.ToString(), RoleType.ProductManager.ToString() });
const string industriesRoute = "/Industries";
Get[industriesRoute + "/{industryIds?}"] = parameters =>
{
var allIndustryDtos = Mapper.Map<IEnumerable<IIndustry>, IEnumerable<IndustryDto>>(repository);
if (!parameters.industryIds.HasValue)
return Response.AsJson(allIndustryDtos);
var filteredIndustries = Enumerable.Empty<Industry>();
if (parameters.industryIds.HasValue)
{
var industryString = (string)parameters.industryIds.Value;
var industryIds = industryString.Split(',').Select(x => new Guid(x));
filteredIndustries = repository.Where(x => industryIds.Contains(x.Id));
}
var industries = filteredIndustries as IList<Industry> ?? filteredIndustries.ToList();
var filteredIndustryDtos = Mapper.Map<IEnumerable<IIndustry>, IEnumerable<IndustryDto>>(industries).ToList();
foreach (var industry in filteredIndustryDtos)
industry.IsSelected = true;
var industryDtos = allIndustryDtos as IList<IndustryDto> ?? allIndustryDtos.ToList();
var response = industries.Any()
? filteredIndustryDtos.Concat(industryDtos).DistinctBy(c => c.Id)
: industryDtos;
return Response.AsJson(response);
};
Post[industriesRoute] = parameters =>
{
var model = Request.Body<dynamic>();
if (model.name.Value == null)
throw new LightstoneAutoException("Could not bind 'Name' value");
publisher.Publish(new CreateIndustry(Guid.NewGuid(), model.name.Value, false));
return Response.AsJson(new { response = "Success!" });
};
Put[industriesRoute] = parameters =>
{
var model = Request.Body<dynamic>();
if (model.id.Value == null && model.name.Value == null)
throw new LightstoneAutoException("Could not bind 'id' or 'Name' value");
publisher.Publish(new RenameIndustry(new Guid(model.id.Value), model.name.Value, false));
return Response.AsJson(new { response = "Success!" });
};
}
示例2: RepositoryTests
private static void RepositoryTests(IRepository<Person> personRepo, Action commitChanges)
{
Console.WriteLine("Testing with '{0}' ", personRepo);
var id = Guid.NewGuid();
var person = new Person {
Id = id,
Name = id.ToString()
};
personRepo.Add(person);
// Commit the changes depending on the provider
commitChanges();
var found = personRepo.Where(p => p.Id == id)
.FirstOrDefault();
Console.Write(found.Name);
}
示例3: GetTagsForMediaObjects
/// <summary>
/// Gets the tags associated with media objects the user has permission to view.
/// </summary>
/// <param name="repo">The metadata tag repository.</param>
/// <returns>A collection of <see cref="Entity.Tag" /> instances.</returns>
/// <remarks>This function is similar to <see cref="GetTagsForAlbums(IRepository{MetadataTagDto})" />, so if a developer
/// modifies it, be sure to check that function to see if it needs a similar change.</remarks>
private IEnumerable<Entity.Tag> GetTagsForMediaObjects(IRepository<MetadataTagDto> repo)
{
var qry = repo.Where(
m =>
m.FKGalleryId == SearchOptions.GalleryId &&
m.Metadata.MetaName == TagName);
if (!String.IsNullOrEmpty(SearchOptions.SearchTerm))
{
qry = qry.Where(m => m.FKTagName.Contains(SearchOptions.SearchTerm));
}
if (SearchOptions.IsUserAuthenticated)
{
if (!UserCanViewRootAlbum)
{
// User can't view the root album, so get a list of the albums she *can* see and make sure our
// results only include albums that are viewable.
var albumIds = SearchOptions.Roles.GetViewableAlbumIdsForGallery(SearchOptions.GalleryId);
qry = qry.Where(a => albumIds.Contains(a.Metadata.MediaObject.FKAlbumId));
}
}
else if (UserCanViewRootAlbum)
{
// Anonymous user, so don't include any private albums in results.
qry = qry.Where(a => !a.Metadata.MediaObject.Album.IsPrivate);
}
else
{
// User is anonymous and does not have permission to view the root album, meaning they
// can't see anything. Return empty collection.
return new List<Entity.Tag>();
}
return qry.GroupBy(t => t.FKTagName).Select(t => new Entity.Tag { Value = t.Key, Count = t.Count() });
}
示例4: PackageModule
public PackageModule(IPublishStorableCommands publisher,
IRepository<Domain.Entities.Packages.Read.Package> readRepo,
INEventStoreRepository<Package> writeRepo, IRepository<State> stateRepo, IEntryPoint entryPoint, IAdvancedBus eBus,
IUserManagementApiClient userManagementApi, IBillingApiClient billingApiClient, IPublishIntegrationMessages integration)
{
Get[PackageBuilderApi.PackageRoutes.RequestIndex.ApiRoute] = _ =>
{
return _.showAll
? Response.AsJson(
from p1 in readRepo
where p1.Version == (from p2 in readRepo where p2.PackageId == p1.PackageId && !p2.IsDeleted select p2.Version).Max()
select p1)
: Response.AsJson(readRepo.Where(x => !x.IsDeleted));
};
Get[PackageBuilderApi.PackageRoutes.RequestLookup.ApiRoute] = parameters =>
{
var filter = ((string)Context.Request.Query["q_word[]"].Value + "").Replace(",", " ");
var pageIndex = 0;
var pageSize = 0;
int.TryParse(Context.Request.Query["page_num"].Value, out pageIndex);
int.TryParse(Context.Request.Query["per_page"].Value, out pageSize);
var industries = ((string)parameters.industryIds.Value + "").Split(',').Select(x => !string.IsNullOrEmpty(x) ? new Guid(x) : new Guid());
var publishedPackages = from p1 in readRepo
where p1.Version == (from p2 in readRepo where p2.PackageId == p1.PackageId select p2.Version).Max()
&& p1.State.Name == StateName.Published &&
p1.Industries.Any(ind => industries.Contains(ind.Id))
&& (p1.Name + "").Trim().ToLower().StartsWith(filter)
select p1;
var packages = new PagedList<Domain.Entities.Packages.Read.Package>(publishedPackages, pageIndex - 1, pageSize, x => !x.IsDeleted);
return Response.AsJson(
new
{
result = packages,
cnt_whole = packages.RecordsFiltered
});
};
Get[PackageBuilderApi.PackageRoutes.RequestUpdate.ApiRoute] = parameters => Response.AsJson(
new
{
Response = new[] { Mapper.Map<IPackage, PackageDto>(writeRepo.GetById(parameters.id)) }
});
Post[PackageBuilderApi.PackageRoutes.Execute.ApiRoute] = parameters =>
{
var apiRequest = this.Bind<ApiRequestDto>();
this.Info(() => StringExtensions.FormatWith("Package Execute Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow));
this.Info(() => StringExtensions.FormatWith("Package Read Initialized, TimeStamp: {0}", DateTime.UtcNow));
var package = writeRepo.GetById(apiRequest.PackageId, true);
this.Info(() => StringExtensions.FormatWith("Package Read Completed, TimeStamp: {0}", DateTime.UtcNow));
if (package == null)
{
this.Error(() => StringExtensions.FormatWith("Package not found:", apiRequest.PackageId));
throw new LightstoneAutoException("Package could not be found");
}
this.Info(() => StringExtensions.FormatWith("PackageBuilder Auth to UserManagement Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow));
var token = Context.Request.Headers.Authorization.Split(' ')[1];
var accountNumber = userManagementApi.Get(token, "/CustomerClient/{id}", new[] { new KeyValuePair<string, string>("id", apiRequest.CustomerClientId.ToString()) }, null);
this.Info(() => StringExtensions.FormatWith("PackageBuilder Auth to UserManagement Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow));
var responses = ((Package)package).Execute(entryPoint, apiRequest.UserId, Context.CurrentUser.UserName,
Context.CurrentUser.UserName, apiRequest.RequestId, accountNumber, apiRequest.ContractId, apiRequest.ContractVersion,
apiRequest.DeviceType, apiRequest.FromIpAddress, "", apiRequest.SystemType, apiRequest.RequestFields, (double)package.CostOfSale, (double)package.RecommendedSalePrice, apiRequest.HasConsent);
// Filter responses for cleaner api payload
this.Info(() => StringExtensions.FormatWith("Package Response Filter Cleanup Initialized for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow));
var filteredResponse = new List<IProvideResponseDataProvider>
{
new ResponseMeta(apiRequest.RequestId, responses.ResponseState())
};
filteredResponse.AddRange(Mapper.Map<IEnumerable<IDataProvider>, IEnumerable<IProvideResponseDataProvider>>(responses));
this.Info(() => StringExtensions.FormatWith("Package Response Filter Cleanup Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow));
integration.SendToBus(new PackageResponseMessage(package.Id, apiRequest.UserId, apiRequest.ContractId, accountNumber,
filteredResponse.Any() ? filteredResponse.AsJsonString() : string.Empty, apiRequest.RequestId, Context != null ? Context.CurrentUser.UserName : "unavailable"));
this.Info(() => StringExtensions.FormatWith("Package Execute Completed for {0}, TimeStamp: {1}", apiRequest.RequestId, DateTime.UtcNow));
return filteredResponse;
};
Post[PackageBuilderApi.PackageRoutes.CommitRequest.ApiRoute] = _ =>
{
var apiRequest = this.Bind<ApiCommitRequestDto>();
var token = Context.Request.Headers.Authorization.Split(' ')[1];
var request = billingApiClient.Get(token, "/Transactions/Request/{requestId}", new[]
{
//.........这里部分代码省略.........
示例5: UserAliasModule
public UserAliasModule(IBus bus, IRepository<ClientUserAlias> userAliasRepository, IRepository<User> usereRepository)
{
Get["/UserAliases/{clientId:guid}"] = _ =>
{
var clientId = (Guid)_.clientId;
var aliases = userAliasRepository.Where(x => x.Client.Id == clientId);
return Response.AsJson(Mapper.Map<IEnumerable<ClientUserAlias>, IEnumerable<UserAliasDto>>(aliases));
};
//TODO: Error checking for file type. Allow csv only
Post["/UserAliases/ImportUsers/FilesUpload/{clientId:guid}"] = _ =>
{
var clientId = (Guid)_.clientId;
var filesUploaded = Request.Files;
var files = new List<FileUploadDto>();
var clientImportUsers = new List<UserAliasDto>();
foreach (var httpFile in filesUploaded)
{
//if (httpFile.ContentType != "text/csv")
//{
// // Response for file upload component
// files.Add(new FileUploadDto
// {
// name = httpFile.Name,
// size = Convert.ToInt32(httpFile.Value.Length),
// error = "File type not allowed"
// });
// break;
//};
// CSV to object
using (var reader = new StreamReader(httpFile.Value))
{
var contents = reader.ReadToEnd().Split('\n');
var csv = from line in contents select line.Split(',').ToArray();
clientImportUsers.AddRange(csv.Skip(1).TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0)
.Select(row => new UserAliasDto
{
UuId = row[0],
FirstName = row[1],
LastName = row[2],
UserName = row[3].Replace("\r", ""),
ClientId = clientId
}));
foreach (var clientImportUser in clientImportUsers)
{
var exists = userAliasRepository.Any(x => x.Client.Id == clientId && x.UserName.Trim().ToLower() == clientImportUser.UserName.Trim().ToLower());
if (exists)
throw new LightstoneAutoException("{0} already exists".FormatWith(clientImportUser.UserName));
var entity = Mapper.Map(clientImportUser, new ClientUserAlias());
bus.Publish(new CreateUpdateEntity(entity, "Create"));
}
}
// Response for file upload component
files.Add(new FileUploadDto
{
name = httpFile.Name,
size = Convert.ToInt32(httpFile.Value.Length),
thumbnailUrl = "http://icons.iconarchive.com/icons/custom-icon-design/pretty-office-2/72/success-icon.png",
deleteType = "DELETE"
});
}
var fileResponseJsonObject = new JObject(new JProperty("files", JsonConvert.SerializeObject(files)));
return Response.AsJson(fileResponseJsonObject);
};
Post["/UserAliases/LinkAlias"] = _ =>
{
var dto = this.Bind<AliasDto>();
var command = new LinkUserAliasCommand(dto.AliasId, dto.CustomerId, dto.UserId);
bus.Publish(command);
return Response.AsJson("Saved!");
};
}