当前位置: 首页>>代码示例>>C#>>正文


C# Repository.Query方法代码示例

本文整理汇总了C#中Repository.Query方法的典型用法代码示例。如果您正苦于以下问题:C# Repository.Query方法的具体用法?C# Repository.Query怎么用?C# Repository.Query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Repository的用法示例。


在下文中一共展示了Repository.Query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CheckPermission2

        public void CheckPermission2()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Permission, Guid> perRepository = new Repository<Permission, Guid>(store);
                PermissionService service = new PermissionService(perRepository);

                IRepository<Employee, Guid> empRepository = new Repository<Employee, Guid>(store);
                IRepository<Entity, Guid> entRepository = new Repository<Entity, Guid>(store);

                //人資部門可以看見Admin
                var operations = service.GetOperationFor(empRepository.Query(s => s.Name == "Fred").First()
                    , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(1, operations.Count);
                Assert.AreEqual("View", operations.First().Comment);

                //業務部門看不見
                var operation2s = service.GetOperationFor(empRepository.Query(s => s.Name == "Kalad").First()
                   , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(0, operation2s.Count);

                //老板通常是有超多權限,但只留較上層的權限
                var operation3s = service.GetOperationFor(empRepository.Query(s => s.Name == "Allen").First()
                  , entRepository.Query(q => q.Name == "Employees").First());

                Assert.AreEqual(1, operation3s.Count);
            }
        }
开发者ID:ephebe,项目名称:MySecurity,代码行数:30,代码来源:PermissionCheckTest.cs

示例2: Here

        public ActionResult Here(int locationId)
        {
            // Get the data
            IRepository repository = new Repository(new CheckInDatabaseContext());

            var location = repository.GetById<Location>(locationId);
            if (location == null)
            {
                return new HttpNotFoundResult();
            }

            var username = HttpContext.User.Identity.Name;

            var user = repository.Query<ApplicationUser>().SingleOrDefault(u => u.UserName == username);
            if (user == null)
            {
                return new HttpNotFoundResult();
            }

            // make a new check in
            var checkIn = new CheckIn();
            checkIn.User = user;
            checkIn.Location = location;
            checkIn.Time = DateTime.Now;
            repository.Insert(checkIn);

            // check to see if this user meets any achievements
            var allCheckins = repository.Query<CheckIn>().Where(c => c.User.Id == user.Id);
            var allAchievements = repository.Query<Achievement>();
            var allLocationIds = repository.Query<Location>().Select(l => l.Id);

            // two in one day?
            if (!allAchievements.Any(a => a.Type == AchievementType.TwoInOneDay) && allCheckins.Count(c => EntityFunctions.TruncateTime(c.Time) == DateTime.Today) > 2)
            {
                var twoInOneDay = new Achievement { Type = AchievementType.TwoInOneDay, User = user, TimeAwarded = DateTime.Now };
                repository.Insert(twoInOneDay);
            }

            // all locations?
            var hasAll = false;
            foreach (var testLocationId in allLocationIds)
            {
                hasAll = hasAll || allCheckins.Any(c => c.Location.Id == testLocationId);
            }

            if (!allAchievements.Any(a => a.Type == AchievementType.AllLocations) && hasAll)
            {
                var allLocations = new Achievement { Type = AchievementType.AllLocations, User = user, TimeAwarded = DateTime.Now };
                repository.Insert(allLocations);
            }

            // some day we'll have hundreds of achievements!

            repository.SaveChanges();

            return RedirectToAction("Index");
        }
开发者ID:manwe651,项目名称:checkin,代码行数:57,代码来源:CheckInController.cs

示例3: BasicCrud

        public void BasicCrud()
        {
            using (var trans = DataSource.BeginTransaction())
            {

                var repo = new Repository<Employee, int>(trans, EmployeeTableName);

                var emp1 = new Employee() { FirstName = "Tom", LastName = "Jones", Title = "President" };
                var echo1 = repo.Insert(emp1);

                Assert.AreNotEqual(0, echo1.EmployeeKey, "EmployeeKey was not set");
                Assert.AreEqual(emp1.FirstName, echo1.FirstName, "FirstName");
                Assert.AreEqual(emp1.LastName, echo1.LastName, "LastName");
                Assert.AreEqual(emp1.Title, echo1.Title, "Title");

                echo1.MiddleName = "G";
                repo.Update(echo1);

                var emp2 = new Employee() { FirstName = "Lisa", LastName = "Green", Title = "VP Transportation", ManagerKey = echo1.EmployeeKey };
                var echo2 = repo.Insert(emp2);
                Assert.AreNotEqual(0, echo2.EmployeeKey, "EmployeeKey was not set");
                Assert.AreEqual(emp2.FirstName, echo2.FirstName, "FirstName");
                Assert.AreEqual(emp2.LastName, echo2.LastName, "LastName");
                Assert.AreEqual(emp2.Title, echo2.Title, "Title");
                Assert.AreEqual(emp2.ManagerKey, echo2.ManagerKey, "ManagerKey");

                var list = repo.GetAll();
                Assert.IsTrue(list.Any(e => e.EmployeeKey == echo1.EmployeeKey), "Employee 1 is missing");
                Assert.IsTrue(list.Any(e => e.EmployeeKey == echo2.EmployeeKey), "Employee 2 is missing");

                var get1 = repo.Get(echo1.EmployeeKey.Value);
                Assert.AreEqual(echo1.EmployeeKey, get1.EmployeeKey);



                var whereSearch1 = repo.Query("FirstName = @FN", new { FN = "Tom" });
                Assert.IsTrue(whereSearch1.Any(x => x.EmployeeKey == echo1.EmployeeKey), "Emp1 should have been returned");
                Assert.IsTrue(whereSearch1.All(x => x.FirstName == "Tom"), "Checking for incorrect return values");

                var whereSearch2 = repo.Query(new { FirstName = "Tom" });
                Assert.IsTrue(whereSearch2.Any(x => x.EmployeeKey == echo1.EmployeeKey), "Emp1 should have been returned");
                Assert.IsTrue(whereSearch2.All(x => x.FirstName == "Tom"), "Checking for incorrect return values");


                repo.Delete(echo2.EmployeeKey.Value);
                repo.Delete(echo1.EmployeeKey.Value);

                var list2 = repo.GetAll();
                Assert.AreEqual(list.Count - 2, list2.Count);

                trans.Commit();
            }

        }
开发者ID:docevaad,项目名称:Chain,代码行数:54,代码来源:TransactionalRepositoryTests.cs

示例4: 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(';'));
        }
开发者ID:jeffjuarez,项目名称:OI---All-Charts,代码行数:26,代码来源:Global.asax.cs

示例5: Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign

        public void Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign()
        {
            List<CallInfo> callis = null;

            using (IDataContextAsync context = new ContestqsoDataContext())
            using (IUnitOfWorkAsync unitOfWorkData = new UnitOfWork(context))
            {
                bool caught = false;
                IRepositoryAsync<CallInfo> _CallinfoRepository = new Repository<CallInfo>(context, unitOfWorkData);

                try
                {
                    TestContext.WriteLine("Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign");
                    //tracked
                    callis = _CallinfoRepository.Query(x => x.UserName == "default")
                        .Include(x => x.Station).Include(x => x.CallSign)
                        .Select().OrderBy(t => t.SessionName).ThenBy(t => t.CallGroup)
                        .ToList();

                }
                catch (Exception ex)
                {
                    TestContext.WriteLine(string.Format("Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign exception {0}", ex.Message));
                    caught = true;
                }
                Assert.IsFalse(caught);  //exception
                Assert.IsNotNull(callis);
                Assert.IsInstanceOfType(callis, typeof(List<CallInfo> ) );
                Assert.AreEqual(3, callis.Count );
                Assert.IsNotNull(callis[0].CallSign);
                Assert.IsNotNull(callis[0].Station);

            }
        }
开发者ID:psws,项目名称:logqso.mvc,代码行数:34,代码来源:IntegrationURFQuertable.cs

示例6: TestCreateMoreParty

        public void TestCreateMoreParty()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Post, Guid> postRepository = new Repository<Post, Guid>(store);
                IRepository<Employee, Guid> employeeRepository = new Repository<Employee, Guid>(store);
                IRepository<PartyHierarchy, Guid> partyHierarchyRepository = new Repository<PartyHierarchy, Guid>(store);
                Employee employee = new Employee()
                {
                    Name = "Bob",
                };

                Post post = new Post()
                {
                    Name = "總經理室副主管",
                };

                Post parentPost = postRepository.Query(q => q.Name == "總經理室主管").First();
                employeeRepository.SaveOrUpdate(employee);
                postRepository.SaveOrUpdate(post);

                PartyService partyService = new PartyService(partyHierarchyRepository);
                partyService.AddAccountability(parentPost, post);
                unitwork.SaveChanges();
                partyService.AddEmployeeToPost(post, employee);
                unitwork.SaveChanges();
            }
        }
开发者ID:ephebe,项目名称:MySecurity,代码行数:28,代码来源:PartyTest.cs

示例7: MyCouponJsonSerializeAndDeserialize_Test

        public void MyCouponJsonSerializeAndDeserialize_Test()
        {
            IRepository repo = new Repository();

            var coupons = repo.Query<CouponView>(x => x.UserID == 443);

            if (coupons != null && coupons.Count > 0)
            {
                var couponDtos = coupons.MapToList<CouponView, CouponDto>().ToList();

                var jsonSerializer = new JavaScriptSerializer();

                var json = jsonSerializer.Serialize(couponDtos);

                if (!string.IsNullOrEmpty(json))
                {
                    couponDtos = jsonSerializer.Deserialize<List<CouponDto>>(json);

                    Assert.IsInstanceOfType(couponDtos[0], typeof(CouponDto));
                }

                var myCouponDto = new MyCouponDto
                {
                    Coupons = couponDtos
                };

                json = jsonSerializer.Serialize(myCouponDto);

                Assert.IsTrue(!string.IsNullOrEmpty(json));
            }
        }
开发者ID:CyranoChen,项目名称:Arsenalcn,代码行数:31,代码来源:MyCoupon_Tests.cs

示例8: Index

        //
        // GET: /Achievement/
        public ActionResult Index()
        {
            // Get the data
            var repository = new Repository(new CheckInDatabaseContext());
            var username = HttpContext.User.Identity.Name;

            ViewBag.Achievements = repository.Query<Achievement>().Where(c => c.User.UserName == username).OrderByDescending(c => c.TimeAwarded).ToList();

            return this.View();
        }
开发者ID:manwe651,项目名称:checkin,代码行数:12,代码来源:AchievementController.cs

示例9: Init

        public void Init()
        {
            IRepository repo = new Repository();

            var list = repo.Query<OrderItem>(x => x.OrderID == ID)
                .FindAll(x => x.IsActive && Product.Cache.Load(x.ProductGuid) != null);

            if (list.Any())
            {
                var oiBase = list.Find(x => Product.Cache.Load(x.ProductGuid).ProductType.Equals(ProductType.MembershipCore));
                if (oiBase != null)
                {
                    var mapperMemShipCore = new MapperConfiguration(cfg =>
                        cfg.CreateMap<OrderItem, OrdrItmMemShipCore>().AfterMap((s, d) => d.Init()))
                        .CreateMapper();

                    OIMembershipCore = mapperMemShipCore.Map<OrdrItmMemShipCore>(oiBase);
                }

                oiBase =
                    list.Find(x => Product.Cache.Load(x.ProductGuid).ProductType.Equals(ProductType.MembershipPremier));
                if (oiBase != null)
                {
                    var mapperMemShipPremier = new MapperConfiguration(cfg =>
                        cfg.CreateMap<OrderItem, OrdrItmMemShipPremier>().AfterMap((s, d) => d.Init()))
                        .CreateMapper();

                    OIMembershipPremier = mapperMemShipPremier.Map<OrdrItmMemShipPremier>(oiBase);
                }

                if (OIMembershipCore != null || OIMembershipPremier != null)
                {
                    UrlOrderView = "iArsenalOrderView_Membership.aspx";
                }
                else
                {
                    throw new Exception("Unable to init Order_Membership.");
                }
            }

            #region Order Status Workflow Info

            var strWorkflow = "{{ \"StatusType\": \"{0}\", \"StatusInfo\": \"{1}\" }}";

            string[] workflowInfo =
            {
                string.Format(strWorkflow, ((int) OrderStatusType.Draft), "未提交"),
                string.Format(strWorkflow, ((int) OrderStatusType.Submitted), "审核中"),
                string.Format(strWorkflow, ((int) OrderStatusType.Confirmed), "已确认")
            };

            StatusWorkflowInfo = workflowInfo;

            #endregion
        }
开发者ID:CyranoChen,项目名称:Arsenalcn,代码行数:55,代码来源:OrderMemberShip.cs

示例10: Execute

        public void Execute(object state)
        {
            var logInfo = new LogInfo
            {
                MethodInstance = MethodBase.GetCurrentMethod(),
                ThreadInstance = Thread.CurrentThread
            };

            try
            {
                _log.Info("Scheduler Start: (AutoUpdateMonthlyRank)", logInfo);

                IRepository repo = new Repository();

                var iDay = DateTime.Today;

                var firstBetDate = repo.Single<Bet>(1).BetTime;

                while (!(iDay.Year <= firstBetDate.Year && iDay.Month < firstBetDate.Month))
                {
                    var winner = GamblerDW.GetTopGamblerMonthly(iDay, RankType.Winner);
                    var loser = GamblerDW.GetTopGamblerMonthly(iDay, RankType.Loser);
                    var rper = GamblerDW.GetTopGamblerMonthly(iDay, RankType.RP);

                    if (winner != null && loser != null)
                    {
                        var day = iDay;
                        var rank = repo.Query<Rank>(x => x.RankYear == day.Year && x.RankMonth == day.Month).FirstOrDefault();

                        if (rank != null)
                        {
                            //update
                            rank.Init(winner, loser, rper);

                            repo.Update(rank);
                        }
                        else
                        {
                            //insert
                            var instance = new Rank { RankYear = day.Year, RankMonth = day.Month };
                            instance.Init(winner, loser, rper);

                            repo.Insert(instance);
                        }
                    }
                    iDay = iDay.AddMonths(-1);
                }

                _log.Info("Scheduler End: (AutoUpdateMonthlyRank)", logInfo);
            }
            catch (Exception ex)
            {
                _log.Warn(ex, logInfo);
            }
        }
开发者ID:CyranoChen,项目名称:Arsenalcn,代码行数:55,代码来源:AutoUpdateMonthlyRank.cs

示例11: TestGetAllParentEntities

        public void TestGetAllParentEntities()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Entity, Guid> repository = new Repository<Entity, Guid>(store);

                EntityService service = new EntityService();
                ICollection<Entity> entities = service.GetAllParentEntities(repository.Query(q => q.Name == "Section").First().Id);
                Assert.AreEqual(1, entities.Count);
            }
        }
开发者ID:ephebe,项目名称:MySecurity,代码行数:11,代码来源:EntityTest.cs

示例12: InsertProducts

        public void InsertProducts()
        {
            using (IDataContextAsync context = new NorthwindContext())
            using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
            {
                IRepositoryAsync<Product> productRepository = new Repository<Product>(context, unitOfWork);

                var newProducts = new[]
                {
                    new Product {ProductName = "One", Discontinued = false, ObjectState = ObjectState.Added},
                    new Product {ProductName = "12345678901234567890123456789012345678901234567890", Discontinued = true, ObjectState = ObjectState.Added},
                    new Product {ProductName = "Three", Discontinued = true, ObjectState = ObjectState.Added},
                    new Product {ProductName = "Four", Discontinued = true, ObjectState = ObjectState.Added},
                    new Product {ProductName = "Five", Discontinued = true, ObjectState = ObjectState.Added}
                };

                foreach (var product in newProducts)
                {
                    try
                    {
                        productRepository.Insert(product);
                        unitOfWork.SaveChanges();
                    }
                    catch (DbEntityValidationException ex)
                    {
                        var sb = new StringBuilder();

                        foreach (var failure in ex.EntityValidationErrors)
                        {
                            sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());

                            foreach (var error in failure.ValidationErrors)
                            {
                                sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                sb.AppendLine();
                            }
                        }

                        Debug.WriteLine(sb.ToString());
                        TestContext.WriteLine(sb.ToString());
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        TestContext.WriteLine(ex.Message);
                    }
                }

                var insertedProduct = productRepository.Query(x => x.ProductName == "One").Select().FirstOrDefault();
                Assert.IsTrue(insertedProduct.ProductName == "One");
            }
        }
开发者ID:tishansoft,项目名称:Asp.net-AngularJS-Example,代码行数:52,代码来源:ProductRepositoryTest.cs

示例13: ActivityConvertTest

        public void ActivityConvertTest()
        {
            IRepository<string> repository = new Repository<string>();
            ProcessDefine processDefine = new ProcessDefine(repository.Query<ProcessDef>().First(o => o.Name == "PatchVirtualMachine").Content);

            //System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            //string ajson = javaScriptSerializer.Serialize(processDefine);
            string json = AgileEAP.Core.JsonConvert.SerializeObject(processDefine, new Newtonsoft.Json.Converters.StringEnumConverter { CamelCaseText = true });
            ProcessDefine processDefine2 = AgileEAP.Core.JsonConvert.DeserializeObject<ProcessDefine>(json, new ActivityConvert());

            Assert.AreEqual(processDefine.Name, processDefine2.Name);
        }
开发者ID:AgileEAP,项目名称:AgileEAP-BPM,代码行数:13,代码来源:WorkflowEngineTest.cs

示例14: ResultIsMarshalled

        public void ResultIsMarshalled()
        {
            using (var repo = new Repository<Model>(new RepositoryConfiguration(),
                                                    new ModelFactory<Model>(() => new Model())))
            {
                var modelResult = new Entity {Name = "A"};
                var marshalledResult = repo.Query(m => modelResult);

                Assert.That(marshalledResult.Name, Is.EqualTo(modelResult.Name), "Inner values should equal");

                Assert.That(ReferenceEquals(modelResult, marshalledResult), Is.Not.True, "Instance should be another");
            }
        }
开发者ID:mikaelharsjo,项目名称:Kiwi.Prevalence,代码行数:13,代码来源:QueryResultsAreMarshalledFixture.cs

示例15: TestAddPartyToOrganization

        public void TestAddPartyToOrganization()
        {
            using (UnitOfWork unitwork = new UnitOfWork(store, dbContextFactory))
            {
                IRepository<Organization, Guid> organRepository = new Repository<Organization, Guid>(store);
                IRepository<Party, Guid> partyRepository = new Repository<Party, Guid>(store);

                Organization org1 = new Organization()
                {
                    Name = "總經理室"
                };

                organRepository.SaveOrUpdate(org1);

                Party party1 = partyRepository.Query(q => q.Name == "總經理室主管").First();
                Party party2 = partyRepository.Query(q => q.Name == "總經理室副主管").First();
                org1.Parties.Add(party1);
                org1.Parties.Add(party2);

                unitwork.SaveChanges();

            }
        }
开发者ID:ephebe,项目名称:MySecurity,代码行数:23,代码来源:OrganTest.cs


注:本文中的Repository.Query方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。