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


C# Repository.Create方法代码示例

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


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

示例1: ShouldFilterByLanguage

        public void ShouldFilterByLanguage()
        {
            using (var session = _documentStore.OpenSession())
            {
                var repository = new Repository(session);
                Enumerable.Range(1, 8).ToList().ForEach(i => repository.Create(new Book { Title = "Book " + i, Language = "Venda" }));
                var book1 = new Book { Title = "Book 9", Language = "Zulu" };
                repository.Create(book1);
                var book2 = new Book { Title = "Book 10", Language = "Xhosa" };
                repository.Create(book2);
                session.SaveChanges();

                Assert.AreEqual(10, repository.Count<Book>());

                var expectedBooks = new List<Book> { book1, book2 };
                var booksController = new BooksController(repository);

                var view = (ViewResult)booksController.Filter(new List<string>() { "Zulu", "Xhosa" }, new List<string>(), new List<string>());

                var filterInformation = (FilterInformation)view.Model;
                var actualBooks = filterInformation.BookInformations.Select(bookInformation => bookInformation.Model).ToList();
                Assert.AreEqual(2, actualBooks.Count());
                Assert.AreEqual(expectedBooks.First().Language, actualBooks.First().Language);
                Assert.AreEqual(expectedBooks.Last().Language, actualBooks.Last().Language);
                Assert.AreEqual(2, filterInformation.Languages.Count());
                Assert.AreEqual("Zulu", filterInformation.Languages.First());
                Assert.AreEqual("Xhosa", filterInformation.Languages.Last());
            }
        }
开发者ID:justinwyer,项目名称:bookworm,代码行数:29,代码来源:BooksControllerTest.cs

示例2: ShouldDisplayOnlyDraftNewsCreatedByCurrentUserWhenListingDraftNews

        public void ShouldDisplayOnlyDraftNewsCreatedByCurrentUserWhenListingDraftNews()
        {
            string userName = "user";

            UsingSession((session) =>
            {
                var repository = new Repository(session);
                var post = new Post { Id = 1, Title = "Post 1", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1), IsDraft = true, Creator = userName };
                repository.Create(post);
                post = new Post { Id = 2, Title = "Post 2", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1), IsDraft = true, Creator = userName };
                repository.Create(post);
                post = new Post { Id = 3, Title = "Post 3", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1), IsDraft = true, Creator = "anotherUser" };
                repository.Create(post);
                var controller = new PostsController(repository);
            });

            UsingSession((session) =>
            {
                WaitForTheLastWrite<Post>(session);

                var httpContextStub = new Mock<HttpContextBase>
                {
                    DefaultValue = DefaultValue.Mock
                };
                var user = Mock.Get(httpContextStub.Object.User);
                user.Setup(u => u.Identity.Name).Returns(userName);

                var controller = new PostsController(new Repository(session));
                controller.ControllerContext = new ControllerContext(httpContextStub.Object, new RouteData(), controller);
                var result = (ViewResult)controller.News(excludeDraft: false);
                var pages = (PagedList.IPagedList<IBasePostInformation>)result.Model;

                Assert.AreEqual(2, pages.Count);
            });
        }
开发者ID:justinwyer,项目名称:bookworm,代码行数:35,代码来源:PostsControllerTest.cs

示例3: Init

        /// <summary>
        /// Creates all resources
        /// </summary>
        public static void Init()
        {
            var resourceRepository = new Repository<Resource>();
         
            if (resourceRepository.Get().Count == 0)
            {

                resourceRepository.Create(
                    new Resource()
                    {
                        Name = "Metal",
                        Description = "Basic resource used to build",
                        InitialValue = 200.0
                    }
                    );

                resourceRepository.Create(
                    new Resource()
                    {
                        Name = "Carbon",
                        Description = "Resource used as basic organic building block",
                        InitialValue = 300.0
                    }
                    );

                resourceRepository.Create(
                    new Resource()
                    {
                        Name = "Fule",
                        Description = "Used to power other buildings",
                        InitialValue = 100.0
                    }
                    );
            }
        }
开发者ID:Rep2,项目名称:Life,代码行数:38,代码来源:ResourceFactory.cs

示例4: DetailsShouldAuthorsBooks

        public void DetailsShouldAuthorsBooks()
        {
            var author1 = new Author()
            {
                Name = "Author1",
                Biography = "Biography1",
                PictureUrl = "myPicture1.jpg",
                CreatedAt = DateTime.UtcNow
            };

            var book1 = new Book
            {
                Title = "Oliver Orphan",
                Author = author1.Name,
                AgeRange = "0~2",
                CreatedAt = DateTime.UtcNow
            };

            var book2 = new Book
            {
                Title = "Oliver Orphan2",
                Author = author1.Name,
                AgeRange = "0~2",
                CreatedAt = DateTime.UtcNow.AddDays(-1)
            };

            UsingSession((session) =>
            {
                var repository = new Repository(session);
                var controller = new AuthorsController(repository);
                controller.Create(author1);

                repository.Create(book1);
                repository.Create(book2);
            });

            using (var session = _documentStore.OpenSession())
            {
                var author = WaitForTheLastWrite<Author>(session);
                var controller = new AuthorsController(new Repository(session));
                var result = (ViewResult) controller.Details(author.Id);
                var authorViewModel = (AuthorViewModel) result.Model;

                AuthorsContollerTestHelper.AssertEqual(authorViewModel.Author, author1);
                var books = authorViewModel.Books;
                Assert.AreEqual(2, books.Count());
                Assert.IsFalse(authorViewModel.HasMoreBooks);

                Assert.AreEqual(book1.Title, books.First().Title);
                Assert.AreEqual(book2.Title, books.Last().Title);
            }
        }
开发者ID:justinwyer,项目名称:bookworm,代码行数:52,代码来源:AuthorsControllerTest.cs

示例5: Run

        public override void Run(string[] args)
        {
            if (args.Length == 0) return;

            URIish source = new URIish(args[0]);

            // guess a name
            string p = source.Path;
            while (p.EndsWith("/"))
                p = p.Substring(0, p.Length - 1);
            int s = p.LastIndexOf('/');
            if (s < 0)
                throw die("Cannot guess local name from " + source);
            string localName = p.Substring(s + 1);
            if (localName.EndsWith(".git"))
                localName = localName.Substring(0, localName.Length - 4);

            if (gitdir == null)
                gitdir = Path.Combine(localName, ".git");

            db = new Repository(new DirectoryInfo(gitdir));
            db.Create();
            db.Config.setBoolean("core", null, "bare", false);
            db.Config.save();

            streamOut.WriteLine("Initialized empty Git repository in " + (new DirectoryInfo(gitdir)).FullName);
            streamOut.Flush();

            saveRemote(source);
            FetchResult r = runFetch();
            Ref branch = guessHEAD(r);
            doCheckout(branch);
        }
开发者ID:drothmaler,项目名称:GitSharp,代码行数:33,代码来源:Clone.cs

示例6: InsertData

        private static void InsertData()
        {
            var repo = new Repository<Status>();

                repo.Create(new Status { Id = 0, Name = "Lost" });
                repo.Create(new Status { Id = 1, Name = "Found" });

            var repog = new Repository<Gender>();

                repog.Create(new Gender { Id = 0, Name = "Male" });
                repog.Create(new Gender { Id = 1, Name = "Female" });

            var repoa = new Repository<Animal>();

                repoa.Create(new Animal { Id = 0, Name = "Dog",Breeds = getDogBreeds()});
                repoa.Create(new Animal { Id = 1, Name = "Cat", Breeds = getCatBreeds()});
        }
开发者ID:GunioRobot,项目名称:DynamicProg,代码行数:17,代码来源:Program.cs

示例7: create

 private void create()
 {
     if (gitdir == null)
         gitdir = bare ? Environment.CurrentDirectory : Path.Combine(Environment.CurrentDirectory, ".git");
     db = new Repository(new DirectoryInfo(gitdir));
     db.Create(bare);
     Console.WriteLine("Initialized empty Git repository in " + (new DirectoryInfo(gitdir)).FullName);
 }
开发者ID:drothmaler,项目名称:GitSharp,代码行数:8,代码来源:Init.cs

示例8: TestCreateWorks

        public void TestCreateWorks()
        {
            Repository repository = new Repository(new SqlConnectionDev());
            Club club = new Club();
            club.Name = "Stirling Kyokushin";
            bool result = repository.Create(club);

            Assert.That(result);
        }
开发者ID:chao226,项目名称:Dapper.Repository,代码行数:9,代码来源:UnitTest1.cs

示例9: AssingTicket

        public static void AssingTicket(User user, Issue issue, Message message, string assignee, TelegramBot bot, Jira jiraConn)
        {
            int state = user.State - 1; //безумный костыль для того, чтобы вычислять статус, который нужно перевсети пользоваетля. Так получилось, что это 3 для 4 статуса, и 5 для 6 статуса.
            string keyboard = null;
            if (state == 3)
            {
                keyboard =
                    "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}";
            }
            try
            {
                issue.Refresh();
                if (issue.Assignee == null & issue.Key.Value.Equals(user.TicketNumber))
                {
                    if (issue.Status.ToString() == "10050")
                    {
                        issue.WorkflowTransition("Распределить");
                    }

                    issue.Assignee = assignee;
                    issue.SaveChanges();

                    user.State = state;
                    user.TicketNumber = "";
                    bot.SendMessage(message.chat.id, "Готово.", keyboard);
                }
                else
                {
                    user.State = state;
                    user.TicketNumber = "";
                    bot.SendMessage(message.chat.id, "Тикет уже распределён", keyboard);
                }
            }
            catch (Exception ex)
            {
                using (var repository = new Repository<DutyBotDbContext>())
                {
                    var logReccord = new Log
                    {
                        Date = DateTime.Now,
                        MessageTipe = "error",
                        UserId = message.chat.id,
                        Operation = "AssingTicket",
                        Exception = ex.GetType() + ": " + ex.Message,
                        AddInfo = issue.Key.Value
                    };
                    repository.Create(logReccord);
                }

                user.State = 3;
                user.TicketNumber = "";
                bot.SendMessage(message.chat.id, "Что-то пошло не так.", "{\"keyboard\": [[\"Проверь тикеты\"], [\"Кто сейчас дежурит?\"], [\"Помоги с дежурством\"], [\"Пока ничего\"]],\"resize_keyboard\":true,\"one_time_keyboard\":true}");

            }
        }
开发者ID:grisha0088,项目名称:DutyBot,代码行数:55,代码来源:JiraAddFuncions.cs

示例10: Handle

        public void Handle(UserEventData userEvent)
        {
            try
            {
                _logger.Info(userEvent.UserEventActionId == UserEventData.UserEventType.Open ? OpenEventReceivedMsg : ClickEventReceivedMsg, userEvent.batch_id, userEvent.subscriber_id, userEvent.list_id);

                //
                // Notes:
                // - We want to count even missing / invalid UserAgent requests
                //
                if (string.IsNullOrEmpty(userEvent.UserAgent))
                {
                    userEvent.UserAgent = InvalidOrMissingUserAgentMsg;
                    userEvent.IsMobile = false;
                    userEvent.IsTablet = false;
                    userEvent.IsiOS = false;
                    userEvent.IsAndroid = false;
                    
                    _logger.Info(InvalidOrMissingUserAgentMsg);
                }
                else
                {
                    //
                    // Notes:
                    //  DO NOT stop the process / message processing because of incorrect User Agent Strings !
                    try
                    {
                        var parser = new UserAgentParser(string.Format("{0}&requestedCapabilities={1}", _settings.ParsingServiceUrl, _settings.ParsingRequestedCapabilities));
                        parser.Parse(userEvent);
                        userEvent.ValidateUserAgent();
                    }
                    catch (Exception e)
                    {
                        _logger.Error(ErrorParsingUserAgentMsg, userEvent.UserAgent, e.Message);
                    }
                }

                using (var context = new UserEventContext())
                {
                    var repository = new Repository<UserEventContext>(context);
                    repository.Create(userEvent);

                    using (var uow = new UnitOfWork<UserEventContext>(context))
                    {
                        uow.Commit();
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error("Error(s) found during a user event processing: {0}", e.Dump());
                throw;
            }
        }
开发者ID:c0d3m0nky,项目名称:mty,代码行数:54,代码来源:UserEventHandler.cs

示例11: Init

        public static void Init()
        {
            var buildingRepository = new Repository<Building>();

            if (buildingRepository.Get().Count == 0)
            {
                buildingRepository.Create(
                    MockData()
                );
            }
        }
开发者ID:Rep2,项目名称:Life,代码行数:11,代码来源:BuildingFactory.cs

示例12: LogAsync

 public static async Task LogAsync(Credentials user, LogActivityType activity, string message)
 {
     using (var repo = new Repository())
     {
         var log = repo.Create<activity_log>();
         log.action_id = (int) activity;
         log.credentials_id = Authentication.Credentials.CredId;
         log.message = message;
         log.created = await repo.GetNowAsync();
         repo.Add(log);
         await repo.SaveChangesAsync();
     }
 }
开发者ID:superbatonchik,项目名称:EduFormManager,代码行数:13,代码来源:DbLogger.cs

示例13: ShouldExcludeDraftPostsWhenListingAllPosts

        public void ShouldExcludeDraftPostsWhenListingAllPosts()
        {
            UsingSession((session) =>
            {
                var repository = new Repository(session);
                var post = new Post { Id = 1, Title = "Post 1", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1) } ;
                repository.Create(post);
                post = new Post { Id = 2, Title = "Post 2", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1) } ;
                repository.Create(post);
                post = new Post { Id = 3, Title = "Post 3", Content = "A Post", UpdatedAt = DateTime.Now.AddMinutes(-1), IsDraft = true} ;
                repository.Create(post);
                var controller = new PostsController(repository);
            });

            UsingSession((session) =>
            {
                WaitForTheLastWrite<Post>(session);
                var controller = new PostsController(new Repository(session));
                var result = (ViewResult)controller.News();
                var pages = (PagedList.IPagedList<IBasePostInformation>)result.Model;

                Assert.AreEqual(2, pages.Count);
            });
        }
开发者ID:justinwyer,项目名称:bookworm,代码行数:24,代码来源:PostsControllerTest.cs

示例14: Register

        /// <summary>
        /// Registers user if email is unique
        /// </summary>
        /// <param name="userViewModel">Entered data</param>
        /// <returns>User if registerd, null otherwise</returns>
        public User Register(UserViewModel userViewModel)
        {
            var usrRepo = new Repository<User>();

            var user = usrRepo.Get(new Dictionary<string, string>() { { "Email", userViewModel.Email } }).FirstOrDefault();

            if (user != null)
            {
                return null;
            }

            var newUser = CreateUser(userViewModel);

            usrRepo.Create(newUser);

            return newUser;
        }
开发者ID:Rep2,项目名称:Life,代码行数:22,代码来源:AuthorisationRepository.cs

示例15: Add_adds_an_entity_to_the_db

        public void Add_adds_an_entity_to_the_db()
        {
            IRepository repo = new Repository(_sessionFactory);

            var post = new Post
                           {
                               Author = "Khaja Minhajuddin",
                               Title = "Mongo Blog",
                               Body = "Sample post here",
                               CreatedOn = DateTime.Now
                           };

            repo.Create(post);

            var savedPost = repo.Get<Post>(post.Id);

            Assert.NotNull(savedPost);
        }
开发者ID:minhajuddin,项目名称:mongo_blog,代码行数:18,代码来源:RepositoryTests.cs


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