public void Get_generation_property_returns_generation_property_from_foreign_key_tree()
        {
            var model = new Model();

            var leftType = new EntityType("Left", model);
            var leftId = leftType.AddProperty("Id", typeof(int), true);
            var leftKey = leftType.AddKey(leftId);

            var rightType = new EntityType("Right", model);
            var rightId1 = rightType.AddProperty("Id1", typeof(int), true);
            var rightId2 = rightType.AddProperty("Id2", typeof(int), true);
            var rightKey = rightType.AddKey(new[] { rightId1, rightId2 });

            var middleType = new EntityType("Middle", model);
            var middleProperty1 = middleType.AddProperty("FK1", typeof(int), true);
            var middleProperty2 = middleType.AddProperty("FK2", typeof(int), true);
            var middleKey1 = middleType.AddKey(middleProperty1);
            var middleFK1 = middleType.AddForeignKey(middleProperty1, leftKey, leftType);
            var middleFK2 = middleType.AddForeignKey(new[] { middleProperty2, middleProperty1 }, rightKey, rightType);

            var endType = new EntityType("End", model);
            var endProperty = endType.AddProperty("FK", typeof(int), true);

            var endFK = endType.AddForeignKey(endProperty, middleKey1, middleType);

            rightId2.RequiresValueGenerator = true;

            Assert.Equal(rightId2, endProperty.GetGenerationProperty());
        }
 public static EntityType EntityType()
 {
     var entityType = new EntityType(typeof(IntKeysPoco));
     entityType.AddProperty("PartitionID", typeof(int)).SetColumnName("PartitionKey");
     entityType.AddProperty("RowID", typeof(int)).SetColumnName("RowKey");
     return entityType;
 }
 public static EntityType EntityType()
 {
     var entityType = new EntityType(typeof(NullablePoco));
     entityType.AddProperty("NullInt", typeof(int?));
     entityType.AddProperty("NullDouble", typeof(double?));
     return entityType;
 }
 public TableEntityAdapterFactoryTests()
 {
     _factory = new TableEntityAdapterFactory();
     _entityType = new EntityType(typeof(PocoTestType));
     _entityType.AddProperty("PartitionKey", typeof(string));
     _entityType.AddProperty("RowKey", typeof(string));
     _entityType.AddProperty("Timestamp", typeof(DateTime));
 }
Exemple #5
0
        public void Can_create_key_from_properties()
        {
            var entityType = new EntityType("E");
            var property1 = entityType.AddProperty(Customer.IdProperty);
            var property2 = entityType.AddProperty(Customer.NameProperty);

            var key = new Key(new[] { property1, property2 });

            Assert.True(new[] { property1, property2 }.SequenceEqual(key.Properties));
        }
 public TestStateEntry WithType(string name)
 {
     var e = new EntityType(name);
     e.AddProperty("PartitionKey", typeof(string), true, false);
     e.AddProperty("RowKey", typeof(string), true, false);
     e.AddProperty("ETag", typeof(string), true, false);
     e.AddProperty("Timestamp", typeof(DateTime), true, false);
     _entityType = e;
     return this;
 }
 public TestStateEntry WithType(Type type)
 {
     var e = new EntityType(type);
     e.AddProperty("PartitionKey", typeof(string));
     e.AddProperty("RowKey", typeof(string));
     e.AddProperty("ETag", typeof(string));
     e.AddProperty("Timestamp", typeof(DateTimeOffset));
     _entityType = e;
     return this;
 }
        public void IsRequired_when_dependent_property_nullable()
        {
            var entityType = new EntityType("E");
            entityType.SetKey(entityType.AddProperty("Id", typeof(int)));
            var dependentProp = entityType.AddProperty("P", typeof(int?));

            var foreignKey = new ForeignKey(entityType.GetKey(), new[] { dependentProp });

            Assert.False(foreignKey.IsRequired);
        }
        public void Select_throws_when_composite_key()
        {
            var selector = CreateSelector();
            var entityType = new EntityType("Entity");
            var property = entityType.AddProperty("Id1", typeof(long));
            property.ValueGenerationOnAdd = ValueGenerationOnAdd.Client;
            entityType.SetKey(property, entityType.AddProperty("Id2", typeof(long)));

            Assert.Throws<NotSupportedException>(() => selector.Select(property));
        }
Exemple #10
0
        public void Can_create_unique_index_from_properties()
        {
            var entityType = new EntityType("E");
            var property1 = entityType.AddProperty(Customer.IdProperty);
            var property2 = entityType.AddProperty(Customer.NameProperty);

            var index = new Index(new[] { property1, property2 }) { IsUnique = true, };

            Assert.True(new[] { property1, property2 }.SequenceEqual(index.Properties));
            Assert.True(index.IsUnique);
        }
Exemple #11
0
        public void Validates_properties_from_same_entity()
        {
            var entityType = new EntityType("E");
            var property1 = entityType.AddProperty(Customer.IdProperty);
            var property2 = entityType.AddProperty(Customer.NameProperty);

            property1.EntityType = new EntityType("E1");
            property2.EntityType = new EntityType("E2");

            Assert.Equal(Strings.FormatInconsistentEntityType("properties"),
                Assert.Throws<ArgumentException>(
                    () => new Key(new[] { property1, property2 })).Message);
        }
        public void Reader_contains_nulls_for_unmatched_properties()
        {
            var entityType = new EntityType("TestType");
            entityType.AddProperty("Prop1", typeof(string));
            entityType.AddProperty("Prop2", typeof(int));
            var buffer = new AtsNamedValueBuffer(new Dictionary<string, EntityProperty>());
            var reader = _factory.Create(entityType, buffer);

            Assert.Equal(2, reader.Count);
            Assert.True(reader.IsNull(0));
            Assert.True(reader.IsNull(1));
            Assert.DoesNotThrow(() => reader.ReadValue<string>(0));
        }
        public void It_adds_composite_key()
        {
            var entityType = new EntityType("John Maynard");
            entityType.AddProperty("PartitionKey", typeof(string));
            entityType.AddProperty("RowKey", typeof(string));

            _convention.Apply(entityType);

            var key = entityType.GetKey();
            Assert.Equal(2, key.Properties.Count);
            Assert.Contains("PartitionKey", key.Properties.Select(p => p.ColumnName()));
            Assert.Contains("RowKey", key.Properties.Select(p => p.ColumnName()));
        }
        public void Can_add_and_remove_properties()
        {
            var entityType = new EntityType(typeof(Customer));

            var property1 = entityType.AddProperty(Customer.IdProperty);
            var property2 = entityType.AddProperty(Customer.NameProperty);

            Assert.True(new[] { property1, property2 }.SequenceEqual(entityType.Properties));

            entityType.RemoveProperty(property1);

            Assert.True(new[] { property2 }.SequenceEqual(entityType.Properties));
        }
        public void Can_create_materializer_for_entity_with_fields()
        {
            var entityType = new EntityType(typeof(SomeEntityWithFields));
            entityType.AddProperty("Id", typeof(int));
            entityType.AddProperty("Foo", typeof(string));
            entityType.AddProperty("Goo", typeof(Guid));

            var factory = new EntityMaterializerSource(new MemberMapper(new FieldMatcher())).GetMaterializer(entityType);

            var gu = Guid.NewGuid();
            var entity = (SomeEntityWithFields)factory(new ObjectArrayValueReader(new object[] { "Fu", gu, 77 }));

            Assert.Equal(77, entity.Id);
            Assert.Equal("Fu", entity.Foo);
            Assert.Equal(gu, entity.Goo);
        }
        public void Members_check_arguments()
        {
            Assert.Equal(
                "type",
                // ReSharper disable once AssignNullToNotNullAttribute
                Assert.Throws<ArgumentNullException>(() => new EntityType((Type)null)).ParamName);

            Assert.Equal(
                "name",
                // ReSharper disable once AssignNullToNotNullAttribute
                Assert.Throws<ArgumentNullException>(() => new EntityType((string)null)).ParamName);

            var entityType = new EntityType(typeof(Random));

            Assert.Equal(
                "propertyInfo",
                // ReSharper disable once AssignNullToNotNullAttribute
                Assert.Throws<ArgumentNullException>(() => entityType.AddProperty((PropertyInfo)null)).ParamName);

            Assert.Equal(
                "property",
                // ReSharper disable once AssignNullToNotNullAttribute
                Assert.Throws<ArgumentNullException>(() => entityType.RemoveProperty(null)).ParamName);

            Assert.Equal(
                Strings.FormatArgumentIsEmpty("name"),
                Assert.Throws<ArgumentException>(() => entityType.TryGetProperty("")).Message);

            Assert.Equal(
                Strings.FormatArgumentIsEmpty("name"),
                Assert.Throws<ArgumentException>(() => entityType.GetProperty("")).Message);
        }
        public void Delegate_getter_is_returned_for_IProperty_property()
        {
            var entityType = new EntityType(typeof(Customer));
            var idProperty = entityType.AddProperty("Id", typeof(int));

            Assert.Equal(7, new ClrPropertyGetterSource().GetAccessor(idProperty).GetClrValue(new Customer { Id = 7 }));
        }
 public void Can_lookup_by_storage_name()
 {
     var entityType = new EntityType("Customer");
     var property = entityType.AddProperty("Name", typeof(string));
     property.SetColumnName("FirstName");
     Assert.Equal(property, entityType.GetPropertyByColumnName("FirstName"));
     Assert.Equal(property, entityType.TryGetPropertyByColumnName("FirstName"));
 }
 public virtual void Apply(EntityType entityType)
 {
     var etag = entityType.TryGetProperty("ETag");
     if (etag == null)
     {
         entityType.AddProperty("ETag", typeof(string), true, true);
     }
 }
        public void M_underscore_matching_field_is_not_used_if_type_is_not_compatible()
        {
            var entityType = new EntityType(typeof(TheDarkSideOfTheMoon));
            var property = entityType.AddProperty("SpeakToMe", typeof(int));
            var propertyInfo = entityType.Type.GetAnyProperty("SpeakToMe");
            var fields = propertyInfo.DeclaringType.GetRuntimeFields().ToDictionary(f => f.Name);

            Assert.Null(new FieldMatcher().TryMatchFieldName(property, propertyInfo, fields));
        }
        public void Can_create_foreign_key()
        {
            var entityType = new EntityType("E");
            var dependentProp = entityType.AddProperty("P", typeof(int));
            var principalProp = entityType.AddProperty("Id", typeof(int));
            entityType.SetKey(principalProp);

            var foreignKey
                = new ForeignKey(entityType.GetKey(), new[] { dependentProp })
                    {
                        IsUnique = true,
                    };

            Assert.Same(entityType, foreignKey.ReferencedEntityType);
            Assert.Same(principalProp, foreignKey.ReferencedProperties.Single());
            Assert.Same(dependentProp, foreignKey.Properties.Single());
            Assert.True(foreignKey.IsUnique);
        }
        public void Get_generation_property_returns_null_for_property_without_generator()
        {
            var model = new Model();

            var entityType = new EntityType("Entity", model);
            var property = entityType.AddProperty("Property", typeof(int), true);

            Assert.Null(property.GetGenerationProperty());
        }
        public void It_requires_both_properties(string onlyProp)
        {
            var entityType = new EntityType("John Maynard");
            entityType.AddProperty(onlyProp, typeof(string));

            _convention.Apply(entityType);

            Assert.Equal(1, entityType.Properties.Count);
            Assert.Null(entityType.TryGetKey());
        }
        private static Property CreateProperty(Type propertyType, ValueGenerationOnAdd valueGeneration)
        {
            var entityType = new EntityType("MyType");
            var property = entityType.AddProperty("MyProperty", propertyType);
            property.ValueGenerationOnAdd = valueGeneration;

            new Model().AddEntityType(entityType);

            return property;
        }
        protected override Model BuildModel()
        {
            var model = new Model();

            var entityType1 = new EntityType("SomeEntity");
            model.AddEntityType(entityType1);
            var key1 = entityType1.AddProperty("Id", typeof(int), shadowProperty: true, concurrencyToken: false);
            key1.ValueGenerationOnSave = ValueGenerationOnSave.WhenInserting;
            key1.ValueGenerationOnAdd = ValueGenerationOnAdd.Client;
            entityType1.SetKey(key1);
            entityType1.AddProperty("Name", typeof(string), shadowProperty: true, concurrencyToken: true);

            var entityType2 = new EntityType("SomeDependentEntity");
            model.AddEntityType(entityType2);
            var key2a = entityType2.AddProperty("Id1", typeof(int), shadowProperty: true, concurrencyToken: false);
            var key2b = entityType2.AddProperty("Id2", typeof(string), shadowProperty: true, concurrencyToken: false);
            entityType2.SetKey(key2a, key2b);
            var fk = entityType2.AddProperty("SomeEntityId", typeof(int), shadowProperty: true, concurrencyToken: false);
            entityType2.AddForeignKey(entityType1.GetKey(), new[] { fk });
            var justAProperty = entityType2.AddProperty("JustAProperty", typeof(int), shadowProperty: true, concurrencyToken: false);
            justAProperty.ValueGenerationOnSave = ValueGenerationOnSave.WhenInserting;
            justAProperty.ValueGenerationOnAdd = ValueGenerationOnAdd.Client;

            var entityType3 = new EntityType(typeof(FullNotificationEntity));
            model.AddEntityType(entityType3);
            entityType3.SetKey(entityType3.AddProperty("Id", typeof(int), shadowProperty: true, concurrencyToken: false));
            entityType3.AddProperty("Name", typeof(string), shadowProperty: true, concurrencyToken: true);

            var entityType4 = new EntityType(typeof(ChangedOnlyEntity));
            model.AddEntityType(entityType4);
            entityType4.SetKey(entityType4.AddProperty("Id", typeof(int), shadowProperty: true, concurrencyToken: false));
            entityType4.AddProperty("Name", typeof(string), shadowProperty: true, concurrencyToken: true);

            var entityType5 = new EntityType("SomeMoreDependentEntity");
            model.AddEntityType(entityType5);
            var key5 = entityType5.AddProperty("Id", typeof(int), shadowProperty: true, concurrencyToken: false);
            entityType5.SetKey(key5);
            var fk5a = entityType5.AddProperty("Fk1", typeof(int), shadowProperty: true, concurrencyToken: false);
            var fk5b = entityType5.AddProperty("Fk2", typeof(string), shadowProperty: true, concurrencyToken: false);
            entityType5.AddForeignKey(entityType2.GetKey(), new[] { fk5a, fk5b });

            return model;
        }
        public void Select_throws_when_non_integer_column_key()
        {
            var selector = CreateSelector();
            var entityType = new EntityType("Entity");
            var property = entityType.AddProperty("Id", typeof(int));
            property.ValueGenerationOnAdd = ValueGenerationOnAdd.Client;
            entityType.SetKey(property);

            Assert.Throws<NotSupportedException>(() => selector.Select(property));
        }
        public void Select_returns_null_when_ValueGenerationOnAdd_is_not_Client()
        {
            var entityType = new EntityType("Entity");
            var property = entityType.AddProperty("Id", typeof(long));
            entityType.SetKey(property);

            var result = CreateSelector().Select(property);

            Assert.Null(result);
        }
        public void Lookup_by_storage_name_returns_null()
        {
            var entityType = new EntityType("Customer");
            entityType.AddProperty("Name", typeof(string));

            Assert.Equal(
                Strings.FormatPropertyWithStorageNameNotFound("FirstName", "Customer"),
                Assert.Throws<ModelItemNotFoundException>(() => entityType.GetPropertyByColumnName("FirstName")).Message);
            Assert.Null(entityType.TryGetPropertyByColumnName("FirstName"));
        }
 public static EntityType EntityType()
 {
     var entityType =
         new EntityType(typeof(PocoTestType));
     foreach (var property in typeof(PocoTestType).GetProperties())
     {
         entityType.AddProperty(property);
     }
     return entityType;
 }
        public void Throws_if_no_match_found_and_no_property_setter()
        {
            var entityType = new EntityType(typeof(TheDarkSide));
            entityType.AddProperty("Time", typeof(string));

            Assert.Equal(
                Strings.FormatNoFieldOrSetter("TheDarkSide", "Time"),
                Assert.Throws<InvalidOperationException>(
                    () => new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType)).Message);
        }
        public IEntityType GetEntityType(Type type)
        {
            var entityType = new EntityType(type);

            var efEntityType = _model.GetEntityType(type);

            foreach (var prop in efEntityType.Properties)
            {
                var property = new Property(entityType, prop.Name, prop.PropertyType)
                {
                    IsNullable = prop.IsNullable,
                    IsReadOnly = prop.IsReadOnly
                };

                entityType.AddProperty(property);
            }

            return(entityType);
        }
Exemple #32
0
        public void It_gets_value_by_storage_name()
        {
            var entityType = new EntityType("TestType");
            var property   = entityType.AddProperty("ClrName", typeof(object));

            property.SetColumnName("StorageName");

            var data = new Dictionary <string, EntityProperty>
            {
                { "StorageName", new EntityProperty(3987) },
                { "ClrName", new EntityProperty(0) },
            };
            var buffer = new AtsNamedValueBuffer(data);

            var reader = _factory.Create(entityType, buffer);

            Assert.Equal(1, reader.Count);
            Assert.Equal(3987, reader.ReadValue <int>(0));
        }
Exemple #33
0
        public void Entry_subscribes_to_INotifyPropertyChanging_and_INotifyPropertyChanged()
        {
            var entityType = new EntityType(typeof(FullNotificationEntity));
            var property   = entityType.AddProperty("Name", typeof(string));

            var entity = new FullNotificationEntity();

            var entryMock = new Mock <StateEntry>();

            entryMock.Setup(m => m.EntityType).Returns(entityType);
            entryMock.Setup(m => m.Entity).Returns(entity);

            new StateEntrySubscriber().SnapshotAndSubscribe(entryMock.Object);

            entity.Name = "George";

            entryMock.Verify(m => m.PropertyChanging(property));
            entryMock.Verify(m => m.PropertyChanged(property));
        }
        public void Every_eventId_has_a_logger_method_and_logs_when_level_enabled()
        {
            var propertyInfo          = typeof(DateTime).GetTypeInfo().GetDeclaredProperty(nameof(DateTime.Now));
            var entityType            = new EntityType(typeof(object), new Model(new ConventionSet()), ConfigurationSource.Convention);
            var property              = new Property("A", typeof(int), propertyInfo, null, entityType, ConfigurationSource.Convention, ConfigurationSource.Convention);
            var otherEntityType       = new EntityType(typeof(object), entityType.Model, ConfigurationSource.Convention);
            var otherProperty         = otherEntityType.AddProperty("A", typeof(int), ConfigurationSource.Convention);
            var otherKey              = otherEntityType.AddKey(otherProperty, ConfigurationSource.Convention);
            var foreignKey            = new ForeignKey(new[] { property }, otherKey, entityType, otherEntityType, ConfigurationSource.Convention);
            var navigation            = new Navigation("N", propertyInfo, null, foreignKey);
            var queryModel            = new QueryModel(new MainFromClause("A", typeof(object), Expression.Constant("A")), new SelectClause(Expression.Constant("A")));
            var includeResultOperator = new IncludeResultOperator(new[] { "Foo" }, Expression.Constant("A"));
            var options = new DbContextOptionsBuilder().UseInMemoryDatabase("D").Options;

            var fakeFactories = new Dictionary <Type, Func <object> >
            {
                { typeof(Type), () => typeof(object) },
                { typeof(DbContext), () => new DbContext(options) },
                { typeof(DbContextOptions), () => options },
                { typeof(QueryModel), () => queryModel },
                { typeof(string), () => "Fake" },
                { typeof(IExpressionPrinter), () => new ExpressionPrinter() },
                { typeof(Expression), () => Expression.Constant("A") },
                { typeof(IEntityType), () => entityType },
                { typeof(IKey), () => new Key(new[] { property }, ConfigurationSource.Convention) },
                { typeof(IPropertyBase), () => property },
                { typeof(IServiceProvider), () => new FakeServiceProvider() },
                { typeof(ICollection <IServiceProvider>), () => new List <IServiceProvider>() },
                { typeof(IReadOnlyList <IPropertyBase>), () => new[] { property } },
                { typeof(IEnumerable <Tuple <MemberInfo, Type> >), () => new[] { new Tuple <MemberInfo, Type>(propertyInfo, typeof(object)) } },
                { typeof(MemberInfo), () => propertyInfo },
                { typeof(IncludeResultOperator), () => includeResultOperator },
                { typeof(IReadOnlyList <Exception>), () => new[] { new Exception() } },
                { typeof(IProperty), () => property },
                { typeof(INavigation), () => navigation },
                { typeof(IForeignKey), () => foreignKey },
                { typeof(InternalEntityEntry), () => new FakeInternalEntityEntry(entityType) },
                { typeof(ISet <object>), () => new HashSet <object>() }
            };

            TestEventLogging(typeof(CoreEventId), typeof(CoreLoggerExtensions), fakeFactories);
        }
Exemple #35
0
        public void Subscriptions_to_INotifyPropertyChanging_and_INotifyPropertyChanged_ignore_unmapped_properties()
        {
            var entityType = new EntityType(typeof(FullNotificationEntity));

            entityType.AddProperty("Name", typeof(string));

            var entity = new FullNotificationEntity();

            var entryMock = new Mock <StateEntry>();

            entryMock.Setup(m => m.EntityType).Returns(entityType);
            entryMock.Setup(m => m.Entity).Returns(entity);

            new StateEntrySubscriber().SnapshotAndSubscribe(entryMock.Object);

            entity.NotMapped = "Formby";

            entryMock.Verify(m => m.PropertyChanging(It.IsAny <IProperty>()), Times.Never);
            entryMock.Verify(m => m.PropertyChanged(It.IsAny <IProperty>()), Times.Never);
        }
        public void FK_back_pointer_is_fixed_up_as_FK_is_added()
        {
            var entityType = new EntityType(typeof(Customer));
            var property   = entityType.AddProperty(Customer.IdProperty);

            entityType.SetKey(property);
            var foreignKey
                = entityType.AddForeignKey(entityType.GetKey(), property);

            Assert.Same(entityType, foreignKey.EntityType);
            Assert.Same(entityType, property.EntityType);

            entityType.RemoveForeignKey(foreignKey);

            // Currently property is not removed when FK is removed
            Assert.Empty(entityType.ForeignKeys);
            Assert.Same(property, entityType.Properties.Single());
            Assert.Same(entityType, foreignKey.EntityType); // TODO: Throw here?
            Assert.Same(entityType, property.EntityType);
        }
Exemple #37
0
        private static IModel CreateModel()
        {
            var model = new Metadata.Model {
                StorageName = "MyDatabase"
            };

            var dependentEntityType = new EntityType("Dependent")
            {
                StorageName = "dbo.MyTable0"
            };
            var principalEntityType = new EntityType("Principal")
            {
                StorageName = "dbo.MyTable1"
            };

            var dependentProperty = dependentEntityType.AddProperty("Id", typeof(int));
            var principalProperty = principalEntityType.AddProperty("Id", typeof(int));

            principalProperty.ValueGenerationStrategy = ValueGenerationStrategy.StoreIdentity;

            model.AddEntityType(principalEntityType);
            model.AddEntityType(dependentEntityType);

            principalProperty.Annotations.Add(new Annotation(
                                                  MetadataExtensions.Annotations.StorageTypeName, "int"));
            dependentProperty.Annotations.Add(new Annotation(
                                                  MetadataExtensions.Annotations.StorageTypeName, "int"));

            dependentEntityType.SetKey(dependentProperty);
            principalEntityType.SetKey(principalProperty);
            dependentEntityType.GetKey().StorageName = "MyPK0";
            principalEntityType.GetKey().StorageName = "MyPK1";

            var foreignKey = dependentEntityType.AddForeignKey(principalEntityType.GetKey(), dependentProperty);

            foreignKey.StorageName = "MyFK";
            foreignKey.Annotations.Add(new Annotation(
                                           MetadataExtensions.Annotations.CascadeDelete, "True"));

            return(model);
        }
Exemple #38
0
        public void Get_generation_property_returns_generation_property_from_foreign_key_chain()
        {
            var model = new Model();

            var firstType     = new EntityType("First", model);
            var firstProperty = firstType.AddProperty("ID", typeof(int), true);
            var firstKey      = firstType.AddKey(firstProperty);

            var secondType       = new EntityType("Second", model);
            var secondProperty   = secondType.AddProperty("ID", typeof(int), true);
            var secondKey        = secondType.AddKey(secondProperty);
            var secondForeignKey = secondType.AddForeignKey(secondProperty, firstKey);

            var thirdType       = new EntityType("Third", model);
            var thirdProperty   = thirdType.AddProperty("ID", typeof(int), true);
            var thirdForeignKey = thirdType.AddForeignKey(thirdProperty, secondKey);

            firstProperty.GenerateValueOnAdd = true;

            Assert.Equal(firstProperty, thirdProperty.GetGenerationProperty());
        }
        public void Generate_model_snapshot_class()
        {
            var model      = new Model();
            var entityType = new EntityType("Entity");

            entityType.SetKey(entityType.AddProperty("Id", typeof(int)));
            model.AddEntityType(entityType);

            var stringBuilder = new IndentedStringBuilder();

            new CSharpModelCodeGenerator().GenerateModelSnapshotClass("MyNamespace", "MyClass", model, stringBuilder);

            Assert.Equal(
                @"using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations.Infrastructure;
using System;

namespace MyNamespace
{
    public class MyClass : ModelSnapshot
    {
        public override IModel Model
        {
            get
            {
                var builder = new ModelBuilder();
                
                builder.Entity(""Entity"", b =>
                    {
                        b.Property<int>(""Id"");
                        b.Key(""Id"");
                    });
                
                return builder.Model;
            }
        }
    }
}",
                stringBuilder.ToString());
        }
        private static IModel CreateModelWithForeignKeys()
        {
            var model = new Model();

            var houseType = new EntityType("Ho!use[]");
            var houseId   = houseType.AddProperty("Id", typeof(int));

            houseType.SetKey(houseId);
            model.AddEntityType(houseType);

            var customerType       = new EntityType(@"Customer");
            var customerId         = customerType.AddProperty("Id", typeof(int));
            var customerFkProperty = customerType.AddProperty("HouseId", typeof(int));

            customerFkProperty.SetColumnName(@"House[""Id]Column");
            customerType.SetSchema("dbo");
            customerType.SetTableName(@"Cus[""om.er]s");
            customerType.SetKey(customerId);
            customerType.GetKey().SetKeyName(@"My[""PK]");
            customerType.GetKey().Annotations.Add(new Annotation(@"My""PK""Annotat!on", @"""Foo"""));
            var customerFk = customerType.AddForeignKey(houseType.GetKey(), customerFkProperty);

            customerFk.SetKeyName(@"My_[""FK]");
            customerFk.Annotations.Add(new Annotation(@"My""FK""Annotation", @"""Bar"""));
            model.AddEntityType(customerType);

            var orderType = new EntityType(@"Order");
            var orderId   = orderType.AddProperty(@"OrderId", typeof(int));
            var orderFK   = orderType.AddProperty(@"CustomerId", typeof(int));

            orderType.SetSchema("dbo");
            orderType.SetKey(orderId);
            orderType.SetTableName(@"Ord[""e.r]s");
            orderType.AddForeignKey(customerType.GetKey(), orderFK);
            orderType.Annotations.Add(new Annotation("Random annotation", "42"));
            model.AddEntityType(orderType);

            return(model);
        }
Exemple #41
0
        public void Every_eventId_has_a_logger_method_and_logs_when_level_enabled()
        {
            var propertyInfo    = typeof(DateTime).GetTypeInfo().GetDeclaredProperty(nameof(DateTime.Now));
            var entityType      = new Model().AddEntityType(typeof(object), ConfigurationSource.Convention);
            var property        = entityType.AddProperty("A", typeof(int), ConfigurationSource.Convention, ConfigurationSource.Convention);
            var otherEntityType = new EntityType(typeof(object), entityType.Model, ConfigurationSource.Convention);
            var otherProperty   = otherEntityType.AddProperty(
                "A", typeof(int), ConfigurationSource.Convention, ConfigurationSource.Convention);
            var otherKey       = otherEntityType.AddKey(otherProperty, ConfigurationSource.Convention);
            var foreignKey     = new ForeignKey(new[] { property }, otherKey, entityType, otherEntityType, ConfigurationSource.Convention);
            var navigation     = new Navigation("N", propertyInfo, null, foreignKey);
            var skipNavigation = new SkipNavigation(
                "SN", propertyInfo, null, entityType, otherEntityType, true, false, ConfigurationSource.Convention);
            var navigationBase = new FakeNavigationBase("FNB", ConfigurationSource.Convention, entityType);

            entityType.Model.FinalizeModel();
            var options = new DbContextOptionsBuilder()
                          .UseInternalServiceProvider(InMemoryFixture.DefaultServiceProvider)
                          .UseInMemoryDatabase("D").Options;

            var fakeFactories = new Dictionary <Type, Func <object> >
            {
                { typeof(Type), () => typeof(object) },
        private static Model BuildModel()
        {
            var model = new Model();

            var entityType = new EntityType(typeof(Banana));
            var property1  = entityType.AddProperty("P1", typeof(int));
            var property2  = entityType.AddProperty("P2", typeof(string));
            var property3  = entityType.AddProperty("P3", typeof(Random));
            var property4  = entityType.AddProperty("P4", typeof(int));
            var property5  = entityType.AddProperty("P5", typeof(string));
            var property6  = entityType.AddProperty("P6", typeof(Random));

            entityType.SetKey(property1, property2, property3);
            entityType.AddForeignKey(entityType.GetKey(), property6, property4, property5);

            model.AddEntityType(entityType);

            return(model);
        }
        public void Can_create_materializer_for_entity_ignoring_shadow_fields()
        {
            var entityType = new EntityType(typeof(SomeEntity));

            entityType.AddProperty("Id", typeof(int));
            entityType.AddProperty("IdShadow", typeof(int), shadowProperty: true, concurrencyToken: false);
            entityType.AddProperty("Foo", typeof(string));
            entityType.AddProperty("FooShadow", typeof(string), shadowProperty: true, concurrencyToken: false);
            entityType.AddProperty("Goo", typeof(Guid));
            entityType.AddProperty("GooShadow", typeof(Guid), shadowProperty: true, concurrencyToken: false);

            var factory = new EntityMaterializerSource(new MemberMapper(new FieldMatcher())).GetMaterializer(entityType);

            var gu     = Guid.NewGuid();
            var entity = (SomeEntity)factory(new ObjectArrayValueReader(new object[] { "Fu", "FuS", gu, Guid.NewGuid(), 77, 777 }));

            Assert.Equal(77, entity.Id);
            Assert.Equal("Fu", entity.Foo);
            Assert.Equal(gu, entity.Goo);
        }
Exemple #44
0
        public virtual ForeignKey CreateForeignKey(
            [NotNull] EntityType principalType,
            [NotNull] EntityType dependentType,
            [CanBeNull] string navigationToPrincipal,
            [CanBeNull] IReadOnlyList <Property> foreignKeyProperties,
            [CanBeNull] IReadOnlyList <Property> referencedProperties,
            bool?isUnique)
        {
            foreignKeyProperties = foreignKeyProperties ?? ImmutableList <Property> .Empty;

            if (foreignKeyProperties.Any() &&
                dependentType.TryGetForeignKey(foreignKeyProperties) != null)
            {
                return(null);
            }

            Key principalKey;

            if (referencedProperties != null &&
                referencedProperties.Any())
            {
                // TODO: Use ConfigurationSource
                principalKey = principalType.GetOrAddKey(referencedProperties);
            }
            else
            {
                // Use the primary key if it is compatible with the FK properties, otherwise return null
                principalKey = principalType.TryGetPrimaryKey();
                if (principalKey == null ||
                    (foreignKeyProperties.Any() &&
                     !principalKey.Properties.Select(p => p.UnderlyingType).SequenceEqual(foreignKeyProperties.Select(p => p.UnderlyingType))))
                {
                    return(null);
                }
            }

            // Create foreign key properties in shadow state if no properties are specified
            if (!foreignKeyProperties.Any())
            {
                var baseName    = (string.IsNullOrEmpty(navigationToPrincipal) ? principalType.SimpleName : navigationToPrincipal) + "Id";
                var isComposite = principalKey.Properties.Count > 1;

                var fkProperties = new List <Property>();
                var index        = 0;
                foreach (var keyProperty in principalKey.Properties)
                {
                    string name;
                    do
                    {
                        name = baseName + (isComposite || index > 0 ? index.ToString() : "");
                        index++;
                    }while (dependentType.TryGetProperty(name) != null);

                    fkProperties.Add(dependentType.AddProperty(name, keyProperty.PropertyType.MakeNullable(), shadowProperty: true));
                }

                foreignKeyProperties = fkProperties;
            }

            var newForeignKey = dependentType.AddForeignKey(foreignKeyProperties, principalKey);

            newForeignKey.IsUnique = isUnique;

            return(newForeignKey);
        }
        public void SetPrimaryKey(EntityType entityType)
        {
            var property = entityType.AddProperty("Id", typeof(int));

            entityType.SetPrimaryKey(property);
        }
Exemple #46
0
        protected override void InvokeInternal(CommandProcessorContext cpc)
        {
            // safety check, this should never be hit
            Debug.Assert(EntityType != null, "InvokeInternal is called when EntityType is null.");
            if (EntityType == null)
            {
                throw new InvalidOperationException("InvokeInternal is called when EntityType is null");
            }

            // check for uniqueness
            string msg;

            if (!ModelHelper.ValidateEntityPropertyName(EntityType, Name, true, out msg))
            {
                throw new CommandValidationFailedException(msg);
            }

            // create the property
            _createdProperty = new ComplexConceptualProperty(EntityType, null, _insertPosition);

            // set the name and add to the parent entity
            _createdProperty.LocalName.Value = Name;
            if (ComplexType != null)
            {
                _createdProperty.ComplexType.SetRefName(ComplexType);
            }
            else if (!String.IsNullOrEmpty(_typeName))
            {
                // separate this name into the namespace and name parts
                string typeNamespace;
                string typeLocalName;
                EFNormalizableItemDefaults.SeparateRefNameIntoParts(_typeName, out typeNamespace, out typeLocalName);

                // look to see if the referenced complex type exists (it may not if they are pasting across models)
                // just search on local name since two models will have different namespaces probably
                ComplexType type = null;
                var         cem  = EntityType.EntityModel as ConceptualEntityModel;
                foreach (var c in cem.ComplexTypes())
                {
                    if (string.Compare(typeLocalName, c.LocalName.Value, StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        type = c;
                        break;
                    }
                }

                // set the complex type reference
                if (type == null)
                {
                    // if we didn't find the complex type locally, write out the type name - but for the local namespace
                    // this will let the user subsequently copy the complex type and this property will start working again
                    var typeSymbol = new Symbol(cem.Namespace.Value, typeLocalName);
                    _createdProperty.ComplexType.SetXAttributeValue(typeSymbol.ToDisplayString());
                }
                else
                {
                    _createdProperty.ComplexType.SetRefName(type);
                }
            }
            else
            {
                _createdProperty.ComplexType.SetXAttributeValue(Resources.ComplexPropertyUndefinedType);
            }

            // runtime does not support nullable complex properties, need to set it to false since the default is true
            _createdProperty.Nullable.Value = BoolOrNone.FalseValue;
            EntityType.AddProperty(_createdProperty);

            XmlModelHelper.NormalizeAndResolve(_createdProperty);
        }
Exemple #47
0
        public void Compare_returns_0_only_for_commands_that_are_equal()
        {
            var mCC = new ModificationCommandComparer();

            var configuration = new DbContext(new DbContextOptions().UseInMemoryStore(persist: false)).Configuration;

            var entityType1 = new EntityType(typeof(object));
            var key1        = entityType1.AddProperty("Id", typeof(int), shadowProperty: true, concurrencyToken: false);

            entityType1.SetKey(key1);
            var stateEntry1 = new MixedStateEntry(configuration, entityType1, new object());

            stateEntry1[key1]       = 0;
            stateEntry1.EntityState = EntityState.Added;
            var modificationCommandAdded = new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator());

            modificationCommandAdded.AddStateEntry(stateEntry1);

            var entityType2 = new EntityType(typeof(object));
            var key2        = entityType2.AddProperty("Id", typeof(int), shadowProperty: true, concurrencyToken: false);

            entityType2.SetKey(key2);
            var stateEntry2 = new MixedStateEntry(configuration, entityType2, new object());

            stateEntry2[key2]       = 0;
            stateEntry2.EntityState = EntityState.Modified;
            var modificationCommandModified = new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator());

            modificationCommandModified.AddStateEntry(stateEntry2);

            var entityType3 = new EntityType(typeof(object));
            var key3        = entityType3.AddProperty("Id", typeof(int), shadowProperty: true, concurrencyToken: false);

            entityType3.SetKey(key3);
            var stateEntry3 = new MixedStateEntry(configuration, entityType3, new object());

            stateEntry3[key3]       = 0;
            stateEntry3.EntityState = EntityState.Deleted;
            var modificationCommandDeleted = new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator());

            modificationCommandDeleted.AddStateEntry(stateEntry3);

            Assert.True(0 == mCC.Compare(modificationCommandAdded, modificationCommandAdded));
            Assert.True(0 == mCC.Compare(null, null));
            Assert.True(0 == mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator()),
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator())));

            Assert.True(0 > mCC.Compare(null, new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator())));
            Assert.True(0 < mCC.Compare(new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator()), null));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator()),
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator()),
                            new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator())));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator()),
                            new ModificationCommand(new SchemaQualifiedName("A", "foo"), new ParameterNameGenerator())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A", "foo"), new ParameterNameGenerator()),
                            new ModificationCommand(new SchemaQualifiedName("A", "dbo"), new ParameterNameGenerator())));

            Assert.True(0 > mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator()),
                            new ModificationCommand(new SchemaQualifiedName("B"), new ParameterNameGenerator())));
            Assert.True(0 < mCC.Compare(
                            new ModificationCommand(new SchemaQualifiedName("B"), new ParameterNameGenerator()),
                            new ModificationCommand(new SchemaQualifiedName("A"), new ParameterNameGenerator())));

            Assert.True(0 > mCC.Compare(modificationCommandModified, modificationCommandAdded));
            Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandModified));

            Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandAdded));
            Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandDeleted));

            Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandModified));
            Assert.True(0 < mCC.Compare(modificationCommandModified, modificationCommandDeleted));
        }
        private static Property CreateProperty(Type propertyType)
        {
            var entityType = new EntityType("MyType");

            return(entityType.AddProperty("MyProperty", propertyType));
        }
        private static Property CreateProperty()
        {
            var entityType = new EntityType("Led");

            return(entityType.AddProperty("Zeppelin", typeof(int)));
        }
        public async Task Can_add_update_delete_end_to_end_using_only_shadow_state()
        {
            var model = new Model();

            var customerType = new EntityType("Customer");

            customerType.SetKey(customerType.AddProperty("Id", typeof(int), shadowProperty: true, concurrencyToken: false));
            customerType.AddProperty("Name", typeof(string), shadowProperty: true, concurrencyToken: false);

            model.AddEntityType(customerType);

            var configuration = new DbContextOptions()
                                .UseModel(model)
                                .UseInMemoryStore()
                                .BuildConfiguration();

            using (var context = new DbContext(configuration))
            {
                // TODO: Better API for shadow state access
                var customerEntry = context.ChangeTracker.StateManager.CreateNewEntry(customerType);
                customerEntry[customerType.GetProperty("Id")]   = 42;
                customerEntry[customerType.GetProperty("Name")] = "Daenerys";

                await customerEntry.SetEntityStateAsync(EntityState.Added);

                await context.SaveChangesAsync();

                customerEntry[customerType.GetProperty("Name")] = "Changed!";
            }

            // TODO: Fix this when we can query shadow entities
            // var customerFromStore = await inMemoryDataStore.Read(customerType).SingleAsync();
            //
            // Assert.Equal(new object[] { 42, "Daenerys" }, customerFromStore);

            using (var context = new DbContext(configuration))
            {
                var customerEntry = context.ChangeTracker.StateManager.CreateNewEntry(customerType);
                customerEntry[customerType.GetProperty("Id")]   = 42;
                customerEntry[customerType.GetProperty("Name")] = "Daenerys Targaryen";

                await customerEntry.SetEntityStateAsync(EntityState.Modified);

                await context.SaveChangesAsync();
            }

            // TODO: Fix this when we can query shadow entities
            // customerFromStore = await inMemoryDataStore.Read(customerType).SingleAsync();
            //
            // Assert.Equal(new object[] { 42, "Daenerys Targaryen" }, customerFromStore);

            using (var context = new DbContext(configuration))
            {
                var customerEntry = context.ChangeTracker.StateManager.CreateNewEntry(customerType);
                customerEntry[customerType.GetProperty("Id")] = 42;

                await customerEntry.SetEntityStateAsync(EntityState.Deleted);

                await context.SaveChangesAsync();
            }

            // TODO: Fix this when we can query shadow entities
            // Assert.Equal(0, await inMemoryDataStore.Read(customerType).CountAsync());
        }
        public void Every_eventId_has_a_logger_method_and_logs_when_level_enabled()
        {
            var propertyInfo    = typeof(DateTime).GetTypeInfo().GetDeclaredProperty(nameof(DateTime.Now));
            var entityType      = new Model().AddEntityType(typeof(object), ConfigurationSource.Convention);
            var property        = entityType.AddProperty("A", typeof(int), ConfigurationSource.Convention, ConfigurationSource.Convention);
            var otherEntityType = new EntityType(typeof(object), entityType.Model, ConfigurationSource.Convention);
            var otherProperty   = otherEntityType.AddProperty(
                "A", typeof(int), ConfigurationSource.Convention, ConfigurationSource.Convention);
            var otherKey       = otherEntityType.AddKey(otherProperty, ConfigurationSource.Convention);
            var foreignKey     = new ForeignKey(new[] { property }, otherKey, entityType, otherEntityType, ConfigurationSource.Convention);
            var navigation     = new Navigation("N", propertyInfo, null, foreignKey);
            var skipNavigation = new SkipNavigation(
                "SN", propertyInfo, null, entityType, otherEntityType, true, false, ConfigurationSource.Convention);
            var navigationBase = new FakeNavigationBase("FNB", ConfigurationSource.Convention, entityType);

            entityType.Model.FinalizeModel();
            var options = new DbContextOptionsBuilder()
                          .UseInternalServiceProvider(InMemoryFixture.DefaultServiceProvider)
                          .UseInMemoryDatabase("D").Options;

            var fakeFactories = new Dictionary <Type, Func <object> >
            {
                { typeof(Type), () => typeof(object) },
                { typeof(DbContext), () => new DbContext(options) },
                { typeof(DbContextOptions), () => options },
                { typeof(string), () => "Fake" },
                { typeof(ExpressionPrinter), () => new ExpressionPrinter() },
                { typeof(Expression), () => Expression.Constant("A") },
                { typeof(IEntityType), () => entityType },
                { typeof(IReadOnlyEntityType), () => entityType },
                { typeof(IConventionEntityType), () => entityType },
                { typeof(IKey), () => new Key(new[] { property }, ConfigurationSource.Convention) },
                { typeof(IPropertyBase), () => property },
                { typeof(IReadOnlyProperty), () => property },
                { typeof(IServiceProvider), () => new FakeServiceProvider() },
                { typeof(ICollection <IServiceProvider>), () => new List <IServiceProvider>() },
                { typeof(IReadOnlyList <IPropertyBase>), () => new[] { property } },
                { typeof(IReadOnlyList <IReadOnlyPropertyBase>), () => new[] { property } },
                {
                    typeof(IEnumerable <Tuple <MemberInfo, Type> >),
                    () => new[] { new Tuple <MemberInfo, Type>(propertyInfo, typeof(object)) }
                },
                { typeof(MemberInfo), () => propertyInfo },
                { typeof(IReadOnlyList <Exception>), () => new[] { new Exception() } },
                { typeof(IProperty), () => property },
                { typeof(INavigation), () => navigation },
                { typeof(IReadOnlyNavigation), () => navigation },
                { typeof(ISkipNavigation), () => skipNavigation },
                { typeof(IReadOnlySkipNavigation), () => skipNavigation },
                { typeof(INavigationBase), () => navigationBase },
                { typeof(IForeignKey), () => foreignKey },
                { typeof(IReadOnlyForeignKey), () => foreignKey },
                { typeof(InternalEntityEntry), () => new FakeInternalEntityEntry(entityType) },
                { typeof(ISet <object>), () => new HashSet <object>() },
                {
                    typeof(IList <IDictionary <string, string> >),
                    () => new List <IDictionary <string, string> > {
                        new Dictionary <string, string> {
                            { "A", "B" }
                        }
                    }
                },
                { typeof(IDictionary <string, string>), () => new Dictionary <string, string>() }
            };

            TestEventLogging(
                typeof(CoreEventId),
                typeof(CoreLoggerExtensions),
                typeof(TestLoggingDefinitions),
                fakeFactories);
        }
Exemple #52
0
        private static IModel BuildModel()
        {
            var model   = new Model();
            var builder = new ModelBuilder(model);

            builder.Annotation("ModelAnnotation1", "ModelValue1");
            builder.Annotation("ModelAnnotation2", "ModelValue2");

            var entityType1 = new EntityType(typeof(KoolEntity1));
            var property    = entityType1.AddProperty("Id1", typeof(int));

            property.StorageName = "MyKey1";
            entityType1.SetKey(property);
            entityType1.AddProperty("Id2", typeof(Guid)).StorageName = "MyKey2";
            entityType1.AddProperty("KoolEntity2Id", typeof(int));
            model.AddEntityType(entityType1);

            var entityType2 = new EntityType(typeof(KoolEntity2));

            entityType2.AddProperty("KoolEntity1Id1", typeof(int));
            entityType2.AddProperty("KoolEntity1Id2", typeof(Guid));
            entityType2.AddProperty("KoolEntity3Id", typeof(int));
            model.AddEntityType(entityType2);

            var entityType3 = new EntityType(typeof(KoolEntity3));

            entityType3.AddProperty("KoolEntity4Id", typeof(int));
            model.AddEntityType(entityType3);

            var entityType4 = new EntityType(typeof(KoolEntity4));

            model.AddEntityType(entityType4);

            var entityType5 = new EntityType(typeof(KoolEntity5));

            model.AddEntityType(entityType5);

            var entityType6 = new EntityType(typeof(KoolEntity6));

            entityType6.AddProperty("Kool5Id", typeof(int));
            model.AddEntityType(entityType6);

            for (var i = 7; i <= 20; i++)
            {
                var type = Type.GetType("Microsoft.Data.Entity.FunctionalTests.Metadata.KoolEntity" + i);

                Assert.NotNull(type);

                model.AddEntityType(new EntityType(type));
            }

            for (var i = 2; i <= 20; i++)
            {
                var type = Type.GetType("Microsoft.Data.Entity.FunctionalTests.Metadata.KoolEntity" + i);

                var entityType = model.GetEntityType(type);
                var id         = entityType.AddProperty(entityType.Type.GetProperty("Id"));
                id.StorageName = "MyKey";
                entityType.SetKey(id);
            }

            for (var i = 1; i <= 20; i++)
            {
                var type = Type.GetType("Microsoft.Data.Entity.FunctionalTests.Metadata.KoolEntity" + i);

                var entityType = model.GetEntityType(type);
                entityType.StorageName = entityType.Name + "Table";

                entityType.Annotations.Add(new Annotation("Annotation1", "Value1"));
                entityType.Annotations.Add(new Annotation("Annotation2", "Value2"));

                var foo = entityType.AddProperty(entityType.Type.GetProperty("Foo" + i));

                foo.Annotations.Add(new Annotation("Foo" + i + "Annotation1", "Foo" + i + "Value1"));
                foo.Annotations.Add(new Annotation("Foo" + i + "Annotation2", "Foo" + i + "Value2"));

                var goo = entityType.AddProperty(entityType.Type.GetProperty("Goo" + i));
            }

            var fk11 = entityType1.AddForeignKey(entityType2.GetKey(), new[] { entityType1.GetProperty("KoolEntity2Id") });
            var fk21 = entityType2.AddForeignKey(entityType1.GetKey(), new[] { entityType2.GetProperty("KoolEntity1Id1") });
            var fk22 = entityType2.AddForeignKey(entityType3.GetKey(), new[] { entityType2.GetProperty("KoolEntity3Id") });
            var fk31 = entityType3.AddForeignKey(entityType4.GetKey(), new[] { entityType3.GetProperty("KoolEntity4Id") });
            var fk61 = entityType6.AddForeignKey(entityType5.GetKey(), new[] { entityType6.GetProperty("Kool5Id") });

            entityType1.AddNavigation(new Navigation(fk11, "NavTo2"));
            entityType1.AddNavigation(new Navigation(fk21, "NavTo2s"));
            entityType2.AddNavigation(new Navigation(fk21, "NavTo1"));
            entityType2.AddNavigation(new Navigation(fk11, "NavTo1s"));
            entityType2.AddNavigation(new Navigation(fk22, "NavTo3"));
            entityType3.AddNavigation(new Navigation(fk22, "NavTo2s"));
            entityType3.AddNavigation(new Navigation(fk31, "NavTo4"));
            entityType4.AddNavigation(new Navigation(fk31, "NavTo3s"));
            entityType5.AddNavigation(new Navigation(fk61, "Kool6s"));
            entityType6.AddNavigation(new Navigation(fk61, "Kool5"));

            return(model);
        }
        public void Every_eventId_has_a_logger_method_and_logs_when_level_enabled()
        {
            var constantExpression = Expression.Constant("A");
            var model      = new Model();
            var entityType = new EntityType(typeof(object), model, ConfigurationSource.Convention);
            var property   = entityType.AddProperty("A", typeof(int), ConfigurationSource.Convention, ConfigurationSource.Convention);
            var key        = entityType.AddKey(property, ConfigurationSource.Convention);
            var foreignKey = new ForeignKey(new List <Property> {
                property
            }, key, entityType, entityType, ConfigurationSource.Convention);
            var index = new Index(new List <Property> {
                property
            }, "IndexName", entityType, ConfigurationSource.Convention);
            var contextServices = RelationalTestHelpers.Instance.CreateContextServices(model.FinalizeModel());

            var fakeFactories = new Dictionary <Type, Func <object> >
            {
                { typeof(string), () => "Fake" },
                { typeof(IList <string>), () => new List <string> {
                      "Fake1", "Fake2"
                  } },
                {
                    typeof(IEnumerable <IUpdateEntry>), () => new List <IUpdateEntry>
                    {
                        new InternalClrEntityEntry(
                            contextServices.GetRequiredService <IStateManager>(),
                            entityType,
                            new object())
                    }
                },
                { typeof(IRelationalConnection), () => new FakeRelationalConnection() },
                { typeof(LoggingDefinitions), () => new TestRelationalLoggingDefinitions() },
                { typeof(DbCommand), () => new FakeDbCommand() },
                { typeof(DbTransaction), () => new FakeDbTransaction() },
                { typeof(DbDataReader), () => new FakeDbDataReader() },
                { typeof(Transaction), () => new CommittableTransaction() },
                { typeof(IMigrator), () => new FakeMigrator() },
                { typeof(Migration), () => new FakeMigration() },
                { typeof(IMigrationsAssembly), () => new FakeMigrationsAssembly() },
                { typeof(MethodCallExpression), () => Expression.Call(constantExpression, typeof(object).GetMethod("ToString")) },
                { typeof(Expression), () => constantExpression },
                { typeof(IEntityType), () => entityType },
                { typeof(IProperty), () => property },
                { typeof(IKey), () => key },
                { typeof(IForeignKey), () => foreignKey },
                { typeof(IIndex), () => index },
                { typeof(TypeInfo), () => typeof(object).GetTypeInfo() },
                { typeof(Type), () => typeof(object) },
                { typeof(ValueConverter), () => new BoolToZeroOneConverter <int>() },
                { typeof(DbContext), () => new FakeDbContext() },
                { typeof(SqlExpression), () => new FakeSqlExpression() }
            };

            TestEventLogging(
                typeof(RelationalEventId),
                typeof(RelationalLoggerExtensions),
                new[]
            {
                typeof(IRelationalConnectionDiagnosticsLogger),
                typeof(IRelationalCommandDiagnosticsLogger)
            },
                new TestRelationalLoggingDefinitions(),
                fakeFactories,
                services => FakeRelationalOptionsExtension.AddEntityFrameworkRelationalDatabase(services),
                new Dictionary <string, IList <string> >
            {
                {
                    nameof(RelationalEventId.CommandExecuting),
                    new List <string>
                    {
                        nameof(IRelationalCommandDiagnosticsLogger.CommandReaderExecuting),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandScalarExecuting),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandNonQueryExecuting),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandReaderExecutingAsync),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandScalarExecutingAsync),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandNonQueryExecutingAsync)
                    }
                },
                {
                    nameof(RelationalEventId.CommandExecuted),
                    new List <string>
                    {
                        nameof(IRelationalCommandDiagnosticsLogger.CommandReaderExecutedAsync),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandScalarExecutedAsync),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandNonQueryExecutedAsync),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandReaderExecuted),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandScalarExecuted),
                        nameof(IRelationalCommandDiagnosticsLogger.CommandNonQueryExecuted)
                    }
                }
            });
        }
        public async Task Can_add_update_delete_end_to_end_using_partial_shadow_state()
        {
            var model = new Model();

            var customerType = new EntityType(typeof(Customer));

            customerType.SetKey(customerType.AddProperty("Id", typeof(int), shadowProperty: false, concurrencyToken: false));
            customerType.AddProperty("Name", typeof(string), shadowProperty: true, concurrencyToken: false);

            model.AddEntityType(customerType);

            var configuration = new DbContextOptions()
                                .UseModel(model)
                                .UseInMemoryStore()
                                .BuildConfiguration();

            var customer = new Customer {
                Id = 42
            };

            using (var context = new DbContext(configuration))
            {
                context.Add(customer);

                // TODO: Better API for shadow state access
                var customerEntry = context.ChangeTracker.Entry(customer).StateEntry;
                customerEntry[customerType.GetProperty("Name")] = "Daenerys";

                await context.SaveChangesAsync();

                customerEntry[customerType.GetProperty("Name")] = "Changed!";
            }

            using (var context = new DbContext(configuration))
            {
                var customerFromStore = context.Set <Customer>().Single();

                Assert.Equal(42, customerFromStore.Id);
                Assert.Equal(
                    "Daenerys",
                    (string)context.ChangeTracker.Entry(customerFromStore).Property("Name").CurrentValue);
            }

            using (var context = new DbContext(configuration))
            {
                var customerEntry = context.ChangeTracker.Entry(customer).StateEntry;
                customerEntry[customerType.GetProperty("Name")] = "Daenerys Targaryen";

                context.Update(customer);

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(configuration))
            {
                var customerFromStore = context.Set <Customer>().Single();

                Assert.Equal(42, customerFromStore.Id);
                Assert.Equal(
                    "Daenerys Targaryen",
                    (string)context.ChangeTracker.Entry(customerFromStore).Property("Name").CurrentValue);
            }

            using (var context = new DbContext(configuration))
            {
                context.Delete(customer);

                await context.SaveChangesAsync();
            }

            using (var context = new DbContext(configuration))
            {
                Assert.Equal(0, context.Set <Customer>().Count());
            }
        }