コード例 #1
0
        public void TestThatConcurrencyViolationsDetected()
        {
            var access1 = _interest.AfterCompleting <Entity1, Entity1>(2);

            _dispatcher.AfterCompleting(2);

            var entity = new Entity1("123", 5);

            _store.Write(entity.Id, entity, 1, _interest);
            _store.Write(entity.Id, entity, 2, _interest);

            Assert.Equal(2, access1.ReadFrom <int>("objectWriteAccumulatedResultsCount"));
            Assert.Equal(Result.Success, access1.ReadFrom <Result>("objectWriteAccumulatedResults"));
            Assert.Equal(Result.Success, access1.ReadFrom <Result>("objectWriteAccumulatedResults"));
            Assert.Equal(0, access1.ReadFrom <int>("objectWriteAccumulatedResultsCount"));

            var access2 = _interest.AfterCompleting <Entity1, Entity1>(3);

            _dispatcher.AfterCompleting(3);

            _store.Write(entity.Id, entity, 1, _interest);
            _store.Write(entity.Id, entity, 2, _interest);
            _store.Write(entity.Id, entity, 3, _interest);

            Assert.Equal(3, access2.ReadFrom <int>("objectWriteAccumulatedResultsCount"));
            Assert.Equal(Result.ConcurrencyViolation, access2.ReadFrom <Result>("objectWriteAccumulatedResults"));
            Assert.Equal(Result.ConcurrencyViolation, access2.ReadFrom <Result>("objectWriteAccumulatedResults"));
            Assert.Equal(Result.Success, access2.ReadFrom <Result>("objectWriteAccumulatedResults"));
        }
コード例 #2
0
            public Entity1 GenerateAppointment()
            {
                var appointment1 = new Entity1 {
                    Id = Guid.NewGuid()
                };

                appointmentStatusHistory1.Entity1   = appointment1;
                appointmentStatusHistory1.Entity1Id = appointment1.Id;
                appointment1.Entities2.Add(appointmentStatusHistory1);
                appointment1.Entity8    = center1;
                appointment1.Entity8Id  = center1.Id;
                appointment1.Entity12   = insurance1;
                appointment1.Entity12Id = insurance1.Id;
                appointment1.Entity14   = patient1;
                appointment1.Entity14Id = patient1.Id;
                appointment1.Entity17   = resource1;
                appointment1.Entity17Id = resource1.Id;
                appointment1.Entity20   = service1;
                appointment1.Entity20Id = service1.Id;
                appointment1.Entity22   = speciality1;
                appointment1.Entity22Id = speciality1.Id;

                patient1.Entities1.Add(appointment1);

                return(appointment1);
            }
コード例 #3
0
 private async Task InsertHardCoded(CancellationToken cancellationToken)
 {
     var entity = new Entity1 {
         AUniqueProperty = "NotAsUniqueAsWeNeed", SomeProperty = "Something"
     };
     await _context.Entity1s.AddAsync(entity, cancellationToken);
 }
コード例 #4
0
        static void Main(string[] args)
        {
            //接口类型
            IShow show = new Entity1()
            {
                ID = 1, Name = "桂素伟"
            };

            Console.WriteLine(show);


            //抽象类型
            Entity entity = new Entity1()
            {
                ID = 1, Name = "桂素伟"
            };

            Console.WriteLine(entity);
            //注1:虽然 类型名{属性名1=属性值,属性名2=属性值,……} 相等,但比较结果是不等的
            Console.WriteLine($"(show == entity结果:{show == entity}");

            //实体类型
            var entity1 = new Entity1()
            {
                ID = 1, Name = "桂素伟"
            };

            Console.WriteLine(entity1);
            Console.WriteLine($"(entity1 == entity结果:{entity1 == entity}");


            AddEntity(entity);

            ReflectionTest(entity1);
        }
コード例 #5
0
        public void TestThatStateStoreWritesAndReadsMetadataOperation()
        {
            var access1 = _interest.AfterCompleting <Entity1, Entity1>(2);

            _dispatcher.AfterCompleting(2);

            var entity         = new Entity1("123", 5);
            var sourceMetadata = Metadata.With("value", "operation");

            _store.Write(entity.Id, entity, 1, sourceMetadata, _interest);
            _store.Read <Entity1>(entity.Id, _interest);

            Assert.Equal(1, access1.ReadFrom <int>("readObjectResultedIn"));
            Assert.Equal(1, access1.ReadFrom <int>("writeObjectResultedIn"));
            Assert.Equal(Result.Success, access1.ReadFrom <Result>("objectReadResult"));
            Assert.Equal(entity, access1.ReadFrom <object>("objectState"));
            Assert.NotNull(access1.ReadFrom <Metadata>("metadataHolder"));
            var metadata = access1.ReadFrom <Metadata>("metadataHolder");

            Assert.True(metadata.HasOperation);
            Assert.Equal("operation", metadata.Operation);

            var readEntity = access1.ReadFrom <Entity1>("objectState");

            Assert.Equal("123", readEntity.Id);
            Assert.Equal(5, readEntity.Value);
        }
コード例 #6
0
        public static void Init(TestContext _)
        {
            _localDbFilePaths        = new string[10];
            _sharedFolderDbFilePaths = new string[10];

            for (int i = 0; i < _localDbFilePaths.Length; i++)
            {
                _localDbFilePaths[i]        = Path.Combine(Properties.Resources.Local, $"{nameof(Add_SqliteDB_BasedOnDifferentDataRowCount_LocalVSSharedFolder_Tests)}{i}.litedb");
                _sharedFolderDbFilePaths[i] = Path.Combine(Properties.Resources.Shared, $"{nameof(Add_SqliteDB_BasedOnDifferentDataRowCount_LocalVSSharedFolder_Tests)}{i}.litedb");
            }

            for (int i = 0; i < _localDbFilePaths.Length; i++)
            {
                if (File.Exists(_localDbFilePaths[i]))
                {
                    File.Delete(_localDbFilePaths[i]);
                }
                using var db = new LiteDatabase(_localDbFilePaths[i]);
                var       collection = db.GetCollection <Entity1>();
                Entity1[] dataRows   = new Entity1[5000];
                for (int j = 0; j < i + 1; j++)
                {
                    for (int r = 0; r < dataRows.Length; r++)
                    {
                        dataRows[r] = AddDataRowsHelper.CreateDataRow <Entity1>(j, r);
                    }
                }
                collection.InsertBulk(dataRows);
                File.Copy(_localDbFilePaths[i], _sharedFolderDbFilePaths[i], true);
            }
        }
        public void TestRedispatch()
        {
            var accessDispatcher = _dispatcher.AfterCompleting(3);

            var entity = new Entity1("123", 5);

            accessDispatcher.WriteUsing("processDispatch", false);
            _store.Write(entity.Id, entity, 1, _interest);

            try
            {
                Thread.Sleep(3000);
            }
            catch
            {
                // ignore
            }

            accessDispatcher.WriteUsing("processDispatch", true);

            accessDispatcher.ReadFromExpecting("dispatchedStateCount", 1);

            var dispatchedStateCount = accessDispatcher.ReadFrom <int>("dispatchedStateCount");

            Assert.True(dispatchedStateCount == 1, "dispatchedStateCount");

            var dispatchAttemptCount = accessDispatcher.ReadFrom <int>("dispatchAttemptCount");

            Assert.True(dispatchAttemptCount > 1, "dispatchAttemptCount");
        }
コード例 #8
0
        [Fact] // CodePlex #2595
        public void Projecting_collection_inside_entity_is_null_comparable()
        {
            var expectedSql =
                @"SELECT 
    1 AS [C1], 
    [Extent1].[Id] AS [Id], 
    CASE WHEN ([Extent1].[Reference1_Id] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C2], 
    [Extent1].[Reference1_Id] AS [Reference1_Id], 
    CASE WHEN ([Extent1].[Reference2_Id] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C3], 
    [Extent1].[Reference2_Id] AS [Reference2_Id]
    FROM [dbo].[Entity1] AS [Extent1]";

            using (var ctx = new Issue2595Context())
            {
                ctx.Database.Delete();

                var entity1 = new Entity1
                {
                    Id         = "1",
                    Reference1 = new Entity2
                    {
                        Id         = "1.1",
                        Collection = new List <Entity3>()
                        {
                            new Entity3 {
                                Id = "1.1.1"
                            },
                            new Entity3 {
                                Id = "1.1.2"
                            }
                        }
                    },
                    Reference2 = new Entity4 {
                        Id = "1.2"
                    }
                };

                var entity2 = new Entity1 {
                    Id = "2", Reference1 = null, Reference2 = new Entity4 {
                        Id = "2.2"
                    }
                };
                var entity3 = new Entity1 {
                    Id = "3", Reference1 = null, Reference2 = null
                };

                ctx.Entities1.Add(entity1);
                ctx.Entities1.Add(entity2);
                ctx.Entities1.Add(entity3);
                ctx.SaveChanges();
            }

            using (var ctx = new Issue2595Context())
            {
                var query = ctx.Entities1.Include(e => e.Reference1).Include("Reference.Collection").Include(e => e.Reference2)
                            .Select(r => new { r.Id, IsNull1 = r.Reference1 == null, r.Reference1, IsNull2 = r.Reference2 == null, r.Reference2 });

                QueryTestHelpers.VerifyDbQuery(query, expectedSql);
            }
        }
コード例 #9
0
        public void ShouldNotBeSlow()
        {
            //List of objects performing slow
            //Entity1
            //Entity17
            //Entity25
            //Entity19
            //Entity15
            //Entity13
            //Entity7
            //Entity5
            //Entity2

            var list       = new List <Entity1>();
            var initialize = new Initialize();

            list.Add(initialize.GenerateAppointment());
            var appointmentsDTO = Mapper.Map <List <EntityDTO1> >(list);
            var list2           = new List <Entity1>();
            var entity          = new Entity1();

            list2.Add(entity);
            var DTOs     = Mapper.Map <List <EntityDTO1> >(list2);
            var list3    = new List <Entity17>();
            var entity17 = new Entity17();

            list3.Add(entity17);
            var DTOs17   = Mapper.Map <List <EntityDTO17> >(list3);
            var list4    = new List <Entity25>();
            var entity25 = new Entity25();

            list4.Add(entity25);
            var DTOs25 = Mapper.Map <List <EntityDTO25> >(list4);
        }
コード例 #10
0
        public async Task SelectNonAbstractDescendantAsyncTest()
        {
            Require.AllFeaturesSupported(ProviderFeatures.Multischema);

            InitializeSchemas();

            BuildDomain(DefaultSchema, DomainUpgradeMode.Recreate, typeof(Entity1)).Dispose();
            var domain = BuildDomain(DefaultSchema, DomainUpgradeMode.PerformSafely, typeof(Entity1), typeof(Entity2));

            using (domain)
                using (var session = domain.OpenSession())
                    using (var transaction = session.OpenTransaction()) {
                        for (var i = 0; i < 10; i++)
                        {
                            _ = new Entity1 {
                                Name        = "1 before test " + i,
                                StringValue = "1 before test " + i
                            };
                            _ = new Entity2 {
                                Name     = "1 before test " + i,
                                IntValue = i
                            };
                        }
                        transaction.Complete();
                    }

            BuildDomain(AlternativeSchema, DomainUpgradeMode.Recreate, typeof(Entity2)).Dispose();
            domain = BuildDomain(AlternativeSchema, DomainUpgradeMode.PerformSafely, typeof(Entity2), typeof(Entity1));

            using (domain)
                using (var session = domain.OpenSession())
                    using (var transaction = session.OpenTransaction()) {
                        for (var i = 0; i < 10; i++)
                        {
                            _ = new Entity1 {
                                Name        = "2 before test " + i,
                                StringValue = "1 before test " + i
                            };
                            _ = new Entity2 {
                                Name     = "2 before test " + i,
                                IntValue = i
                            };
                        }
                        transaction.Complete();
                    }

            domain = await BuildDomainAsync(DefaultSchema, DomainUpgradeMode.Validate, typeof(Entity1), typeof(Entity2));

            await using (domain) {
                var nodeConfiguration = new NodeConfiguration(AlternativeSchema)
                {
                    UpgradeMode = DomainUpgradeMode.Validate
                };
                nodeConfiguration.SchemaMapping.Add(DefaultSchema, AlternativeSchema);
                _ = await domain.StorageNodeManager.AddNodeAsync(nodeConfiguration);

                RunTest(domain, WellKnown.DefaultNodeId, NonAbstractTypesTestBody);
                RunTest(domain, AlternativeSchema, NonAbstractTypesTestBody);
            }
        }
コード例 #11
0
ファイル: HfPreach.cs プロジェクト: piperlolot/LegendsViewer
        public override string Print(bool link = true, DwarfObject pov = null)
        {
            string eventString = GetYearTime();

            eventString += SpeakerHf.ToLink(link, pov, this);
            eventString += " preached to ";
            eventString += Entity1.ToLink(link, pov, this);
            switch (Topic)
            {
            case PreachTopic.SetEntity1AgainstEntity2:
                eventString += ", inveighing against ";
                break;

            case PreachTopic.Entity1ShouldLoveEntity2:
                eventString += ", urging love to be shown to ";
                break;
            }
            eventString += Entity2.ToLink(link, pov, this);
            if (Site != null)
            {
                eventString += " at ";
                eventString += Site.ToLink(link, pov, this);
            }
            eventString += PrintParentCollection(link, pov);
            eventString += ".";
            return(eventString);
        }
コード例 #12
0
        public void GuidEntityEqualsWithTwoNullsEntitiesSameTypeReturnTrue()
        {
            Entity1 e1       = null;
            Entity1 e2       = null;
            var     equality = Equals(e1, e2);

            Assert.AreEqual(true, equality);
        }
コード例 #13
0
 public BindingFallbacksViewModel()
 {
     Title     = "Binding Fallbacks";
     MyEntity1 = new Entity1();
     MyEntity2 = new Entity2 {
         Title = null
     };
 }
コード例 #14
0
        public void GuidEntityEqualsWithTwoTransientEntitiesReturnFalse()
        {
            Entity1 e1       = new Entity1();
            Entity1 e2       = new Entity1();
            var     equality = Equals(e1, e2);

            Assert.AreEqual(false, equality);
        }
コード例 #15
0
        public void Collection_CurrentValueGetsCollection()
        {
            var entity      = new Entity1();
            var entityEntry = new InMemoryCrudRepository.EntityEntry(entity, EntityState.Unchanged);
            InMemoryDbEntityEntry <Entity1> sut = new InMemoryDbEntityEntry <Entity1>(entityEntry);

            sut.Collection(x => x.Children).CurrentValue.Should().BeSameAs(entity.Children);
        }
コード例 #16
0
        public void Reference_CurrentValueGetsProperty()
        {
            var entity      = new Entity1();
            var entityEntry = new InMemoryCrudRepository.EntityEntry(entity, EntityState.Unchanged);
            InMemoryDbEntityEntry <Entity1> sut = new InMemoryDbEntityEntry <Entity1>(entityEntry);

            sut.Reference(x => x.Other).CurrentValue.Should().BeSameAs(entity.Other);
        }
 public void Test01()
 {
     using (var session = Domain.OpenSession())
         using (var tx = session.OpenTransaction()) {
             _ = new Entity1();
             _ = new Entity2();
         }
 }
コード例 #18
0
        public void GuidEntityEqualsWithOneNullEntityReturnFalse()
        {
            Entity1 e1       = new Entity1();
            Entity1 e2       = null;
            var     equality = Equals(e1, e2);

            Assert.AreEqual(false, equality);
        }
コード例 #19
0
 public Entity1ViewModel(Entity1 entity)
 {
     this.Id        = entity.Id;
     this.name      = entity.Property1;
     this.longitude = entity.Property2;
     this.latitude  = entity.Property3;
     this.Entity2   = new Entity2ViewModel(entity.Entity2);
 }
        public async Task <string> Handle(CreateEntity1Command request, CancellationToken cancellationToken)
        {
            var @new = new Entity1(request.Name);

            this._entity1Repository.Create(@new);

            return(@new.Id);
        }
コード例 #21
0
        public void GuidEntityEqualsWithTwoNullsEntitiesDifferentTypeReturnFalse()
        {
            Entity1 e1       = new Entity1();
            Entity2 e2       = new Entity2();
            var     equality = Equals(e1, e2);

            Assert.AreEqual(false, equality);
        }
コード例 #22
0
        public void IdTest()
        {
            var entity = new Entity1("5");

            var entity2 = new Entity1("12");

            Assert.AreEqual(false, entity.Equals(entity2));
        }
コード例 #23
0
        public void GuidEntityEqualsWithSameTransientEntitieReturnTrue()
        {
            Entity1 e1       = new Entity1();
            Entity1 e2       = e1;
            var     equality = Equals(e1, e2);

            Assert.AreEqual(true, equality);
        }
コード例 #24
0
        public async Task <string> Handle(CreateEntity1Command request, CancellationToken cancellationToken)
        {
            var @new = new Entity1(request.Name);

            this._entity1Repository.Add(@new);

            await this._unitOfWork.SaveEntitiesAsync();

            return(@new.Id);
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: neildobson-au/IdSetter
        static void Main(string[] args)
        {
            var x = new Entity1();

            x.SetId(3);

            var y = new Entity1();

            y.SetId(4);
        }
        public void MySqlModeGeneration()
        {
            Require.AllFeaturesNotSupported(ProviderFeatures.Sequences);
            Require.AllFeaturesSupported(ProviderFeatures.AutoIncrementSettingsInMemory);

            using (var session = Domain.OpenSession()) {
                foreach (var keyGenerator in Domain.Configuration.KeyGenerators)
                {
                    CheckGeneratorsAfterDomainBuilded(keyGenerator, session, 0);
                }
            }
            using (var session = Domain.OpenSession())
                using (session.Activate())
                    using (var transaction = session.OpenTransaction()) {
                        for (int i = 0; i < 1; i++)
                        {
                            var entity = new Entity1();
                        }
                    }
            using (var session = Domain.OpenSession()) {
                foreach (var keyGenerator in Domain.Configuration.KeyGenerators)
                {
                    CheckGeneratorsAfterDomainBuilded(keyGenerator, session, 1);
                }
            }
            using (var session = Domain.OpenSession())
                using (session.Activate())
                    using (var transaction = session.OpenTransaction()) {
                        for (int i = 0; i < 120; i++)
                        {
                            var entity = new Entity1();
                        }
                    }

            using (var session = Domain.OpenSession()) {
                foreach (var keyGenerator in Domain.Configuration.KeyGenerators)
                {
                    CheckGeneratorsAfterDomainBuilded(keyGenerator, session, 1);
                }
            }
            using (var session = Domain.OpenSession())
                using (session.Activate())
                    using (var transaction = session.OpenTransaction()) {
                        for (int i = 0; i < 250; i++)
                        {
                            var entity = new Entity1();
                        }
                    }
            using (var session = Domain.OpenSession()) {
                foreach (var keyGenerator in Domain.Configuration.KeyGenerators)
                {
                    CheckGeneratorsAfterDomainBuilded(keyGenerator, session, 1);
                }
            }
        }
コード例 #27
0
        private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var activity = await result as Activity;
            //    private static async void Response(IDialogContext context, Activity message)
            //{
            //  Activity activity = new Activity();
            var response = await Luis.GetResponse(activity.Text);

            if (response != null)
            {
                var intent = new Intent();
                var entity = new Entity1();

                string laptop  = string.Empty;
                string atm     = string.Empty;
                string service = string.Empty;

                foreach (var item in response.entities)
                {
                    switch (item.type.ToLower())
                    {
                    case "laptop repair":
                        laptop = item.entity;
                        break;

                    case "atm machine":
                        atm = item.entity;
                        break;

                    case "service line":
                        service = item.entity;
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(laptop))
                {
                    // return our reply to the user
                    await context.PostAsync($"Hello, {laptop} available to A-3F, B-2F, D-3F");
                }
                else if (!string.IsNullOrEmpty(atm))
                {
                    await context.PostAsync($"Hello, {atm} available to A-Ground Floor, D-Cafeteria");
                }
                else if (!string.IsNullOrEmpty(service))
                {
                    await context.PostAsync($"Hello, {service} are SI, DD, AI ");
                }
                else
                {
                    await context.PostAsync($"No result found");
                }
            }
        }
コード例 #28
0
        public void CannotEquateObjectsWithSameIdButDifferentTypes()
        {
            var obj1 = new Entity1();
            var obj2 = new Entity2();

            EntityIdSetter.SetIdOf(obj1, 1);
            EntityIdSetter.SetIdOf(obj2, 1);

            // ReSharper disable once SuspiciousTypeConversion.Global
            obj1.Equals(obj2).Should().BeFalse();
        }
コード例 #29
0
        public void GetContextEntityByReferenceTest()
        {
            IEntity entity;
            Context context = new Context();

            context.Add <TestRelationship>(entity = new Entity1(), new Entity2());
            context.Add <TestRelationship>(new Entity2(), new Entity3());
            var entities = context.Get(entity);

            Assert.IsTrue(entities.Count() == 1, "Expected 1 matching entity.");
            Assert.IsTrue(entities.Single().ConcreteEntity == entity, "Unexpected concrete entity.");
        }
コード例 #30
0
        public void Add100DataRowsToSharedFolderDb(int dbFilePathIndex)
        {
            using var dbContext = new SqliteDBContext(_sharedFolderDbFilePaths[dbFilePathIndex]);
            var dataRows = new Entity1[100];

            for (int i = 0; i < 100; i++)
            {
                dataRows[i] = AddDataRowsHelper.CreateDataRow <Entity1>(dbFilePathIndex, i + 5000);
            }
            dbContext.AddRange(dataRows);
            dbContext.SaveChanges();
            Assert.AreEqual(100, dbContext.Table1.Where(i => i.BatchId == dbFilePathIndex && i.RowNo >= 5000).Count());
        }
			public async void Must_add_entity_if_entity_is_not_cached()
			{
				var observer = MockRepository.GenerateMock<ISessionObserver<CacheKey, object>>();

				using (INonTransactionalCacheKeySession session = await SessionManager.Enroll(observer))
				{
					Guid id = Guid.NewGuid();
					var entity = new Entity1();

					session.EntityWasPersisted(new CacheEntity<object>(entity, id));

					observer.AssertWasCalled(arg => arg.EntityPersisted(session, entity.GetType(), id));
				}
			}
コード例 #32
0
        [Fact] // CodePlex #2595
        public void Projecting_collection_of_DTOs_inside_DTO_is_null_comparable()
        {
            var expectedSql =
@"SELECT 
    [Project1].[C1] AS [C1], 
    [Project1].[Id] AS [Id], 
    [Project1].[C2] AS [C2], 
    [Project1].[Reference1_Id] AS [Reference1_Id], 
    [Project1].[C3] AS [C3], 
    [Project1].[Reference2_Id] AS [Reference2_Id], 
    [Project1].[C4] AS [C4], 
    [Project1].[Id1] AS [Id1]
    FROM ( SELECT 
        [Extent1].[Id] AS [Id], 
        [Extent1].[Reference1_Id] AS [Reference1_Id], 
        [Extent1].[Reference2_Id] AS [Reference2_Id], 
        1 AS [C1], 
        cast(0 as bit) AS [C2], 
        cast(0 as bit) AS [C3], 
        [Extent2].[Id] AS [Id1], 
        CASE WHEN ([Extent2].[Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C4]
        FROM  [dbo].[Entity1] AS [Extent1]
        LEFT OUTER JOIN [dbo].[Entity3] AS [Extent2] ON [Extent2].[Entity2_Id] = [Extent1].[Reference1_Id]
    )  AS [Project1]
    ORDER BY [Project1].[Id] ASC, [Project1].[C4] ASC";

            using (var ctx = new Issue2595Context())
            {
                ctx.Database.Delete();

                var entity1 = new Entity1
                {
                    Id = "1",
                    Reference1 = new Entity2
                    {
                        Id = "1.1",
                        Collection = new List<Entity3>()
                        {
                            new Entity3 { Id = "1.1.1" },
                            new Entity3 { Id = "1.1.2" }
                        }
                    },
                    Reference2 = new Entity4 { Id = "1.2" }
                };

                var entity2 = new Entity1 { Id = "2", Reference1 = null, Reference2 = new Entity4 { Id = "2.2" } };
                var entity3 = new Entity1 { Id = "3", Reference1 = null, Reference2 = null };

                ctx.Entities1.Add(entity1);
                ctx.Entities1.Add(entity2);
                ctx.Entities1.Add(entity3);
                ctx.SaveChanges();
            }

            using (var ctx = new Issue2595Context())
            {
                var query = ctx.Entities1.Select(e => new DTO1
                {
                    Id = e.Id,
                    Reference1 = new DTO2
                    {
                        Id = e.Reference1.Id,
                        Collection = e.Reference1.Collection.Select(c => new DTO3 { Id = c.Id })
                    },
                    Reference2 = new DTO4 {  Id = e.Reference2.Id }
                }).Select(r => new { r.Id, IsNull1 = r.Reference1 == null, r.Reference1, IsNull2 = r.Reference2 == null, r.Reference2 });

                QueryTestHelpers.VerifyDbQuery(query, expectedSql);
                var results = query.ToList();

                Assert.Equal(3, results.Count);
                Assert.True(results.Select(r => r.IsNull1).All(r => !r));
                Assert.True(results.Select(r => r.IsNull2).All(r => !r));
                Assert.True(results.Select(r => r.Reference1).All(r => r != null));
                Assert.True(results.Select(r => r.Reference2).All(r => r != null));
            }
        }
コード例 #33
0
        [Fact] // CodePlex #2595
        public void Projecting_collection_inside_entity_is_null_comparable()
        {
            var expectedSql =
@"SELECT 
    1 AS [C1], 
    [Extent1].[Id] AS [Id], 
    CASE WHEN ([Extent1].[Reference1_Id] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C2], 
    [Extent1].[Reference1_Id] AS [Reference1_Id], 
    CASE WHEN ([Extent1].[Reference2_Id] IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C3], 
    [Extent1].[Reference2_Id] AS [Reference2_Id]
    FROM [dbo].[Entity1] AS [Extent1]";

            using (var ctx = new Issue2595Context())
            {
                ctx.Database.Delete();

                var entity1 = new Entity1
                {
                    Id = "1",
                    Reference1 = new Entity2
                    {
                        Id = "1.1",
                        Collection = new List<Entity3>()
                        {
                            new Entity3 { Id = "1.1.1" },
                            new Entity3 { Id = "1.1.2" }
                        }
                    },
                    Reference2 = new Entity4 { Id = "1.2" }
                };

                var entity2 = new Entity1 { Id = "2", Reference1 = null, Reference2 = new Entity4 { Id = "2.2" } };
                var entity3 = new Entity1 { Id = "3", Reference1 = null, Reference2 = null };

                ctx.Entities1.Add(entity1);
                ctx.Entities1.Add(entity2);
                ctx.Entities1.Add(entity3);
                ctx.SaveChanges();
            }

            using (var ctx = new Issue2595Context())
            {
                var query = ctx.Entities1.Include(e => e.Reference1).Include("Reference.Collection").Include(e => e.Reference2)
                    .Select(r => new { r.Id, IsNull1 = r.Reference1 == null, r.Reference1, IsNull2 = r.Reference2 == null, r.Reference2 });

                QueryTestHelpers.VerifyDbQuery(query, expectedSql);
            }
        }
			public async void Must_throw_exception_if_entity_being_removed_is_not_cached()
			{
				using (INonTransactionalCacheKeySession session = await SessionManager.Enroll())
				{
					var entity = new Entity1();

					Assert.Throws<SessionException>(() => session.RemoveEntity(entity));
				}
			}
			public async void Must_throw_exception_if_caching_the_same_entity_more_than_once()
			{
				using (INonTransactionalCacheKeySession session = await SessionManager.Enroll())
				{
					var entity = new Entity1();

					Assert.Throws<SessionException>(
						() => session.EntitiesWereFound(
							new CacheKey("test"),
							new[]
								{
									new CacheEntity<object>(entity, Guid.NewGuid()),
									new CacheEntity<object>(entity, Guid.NewGuid())
								}),
						"Cannot cache same entity more than once.");
				}
			}
			public async void Must_throw_exception_if_same_entity_is_added_with_different_id()
			{
				using (INonTransactionalCacheKeySession session = await SessionManager.Enroll())
				{
					var entity = new Entity1();
					var cacheEntity1 = new CacheEntity<object>(entity, Guid.NewGuid());
					var cacheEntity2 = new CacheEntity<object>(entity, Guid.NewGuid());

					session.EntityWasPersisted(cacheEntity1);
					Assert.Throws<SessionException>(() => session.EntityWasPersisted(cacheEntity2));
				}
			}