public void Can_read_nulls()
        {
            var entityType = new Model().AddEntityType(typeof(SomeEntity));
            entityType.GetOrAddProperty("Id", typeof(int));
            entityType.GetOrAddProperty("Foo", typeof(string));
            entityType.GetOrAddProperty("Goo", typeof(Guid?));

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

            var entity = (SomeEntity)factory(new ValueBuffer(new object[] { null, null, 77 }));

            Assert.Equal(77, entity.Id);
            Assert.Null(entity.Foo);
            Assert.Null(entity.Goo);
        }
        public void Constructor_throws_when_principal_and_depedent_property_count_do_not_match()
        {
            var dependentType = new Model().AddEntityType("D");
            var principalType = new Model().AddEntityType("P");

            var dependentProperty1 = dependentType.GetOrAddProperty("P1", typeof(int), shadowProperty: true);
            var dependentProperty2 = dependentType.GetOrAddProperty("P2", typeof(int), shadowProperty: true);

            principalType.GetOrSetPrimaryKey(principalType.GetOrAddProperty("Id", typeof(int), shadowProperty: true));

            Assert.Equal(
                Strings.ForeignKeyCountMismatch("{'P1', 'P2'}", "D", "{'Id'}", "P"),
                Assert.Throws<InvalidOperationException>(
                    () => new ForeignKey(new[] { dependentProperty1, dependentProperty2 }, principalType.GetPrimaryKey(), principalType)).Message);
        }
        public void Delegate_getter_is_returned_for_IProperty_property()
        {
            var entityType = new Model().AddEntityType(typeof(Customer));
            var idProperty = entityType.GetOrAddProperty("Id", typeof(int));

            Assert.Equal(7, new ClrPropertyGetterSource().GetAccessor(idProperty).GetClrValue(new Customer { Id = 7 }));
        }
        public void M_underscore_matching_field_is_not_used_if_type_is_not_compatible()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSideOfTheMoon));
            var property = entityType.GetOrAddProperty("SpeakToMe", typeof(int));
            var propertyInfo = entityType.ClrType.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 Model().AddEntityType("E");
            var dependentProp = entityType.GetOrAddProperty("P", typeof(int), shadowProperty: true);
            var principalProp = entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true);
            entityType.GetOrSetPrimaryKey(principalProp);

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

            Assert.Same(entityType, foreignKey.PrincipalEntityType);
            Assert.Same(principalProp, foreignKey.PrincipalKey.Properties.Single());
            Assert.Same(dependentProp, foreignKey.Properties.Single());
            Assert.True(foreignKey.IsUnique.Value);
            Assert.Same(entityType.GetPrimaryKey(), foreignKey.PrincipalKey);
        }
        public void Throws_if_no_match_found_and_no_property_setter()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSide));
            entityType.GetOrAddProperty("Time", typeof(int));

            Assert.Equal(
                Strings.NoFieldOrSetter(typeof(TheDarkSide).FullName, "Time"),
                Assert.Throws<InvalidOperationException>(
                    () => new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType)).Message);
        }
        public void Delegate_setter_can_set_reference_type_property()
        {
            var entityType = new Model().AddEntityType(typeof(Customer));
            var idProperty = entityType.GetOrAddProperty("Content", typeof(string));

            var customer = new Customer { Id = 7 };

            new ClrPropertySetterSource().GetAccessor(idProperty).SetClrValue(customer, "MyString");

            Assert.Equal("MyString", customer.Content);
        }
        public void Annotated_field_name_is_used_if_present()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSide));
            var property = entityType.GetOrAddProperty("SpeakToMe", typeof(int));
            property["BackingField"] = "fieldForSpeak";

            var mapping = new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType).Single();

            Assert.Same(property, mapping.Item1);
            Assert.Equal("fieldForSpeak", mapping.Item2.Name);
        }
        public void Can_create_materializer_for_entity_with_fields()
        {
            var entityType = new Model().AddEntityType(typeof(SomeEntityWithFields));
            entityType.GetOrAddProperty("Enum", typeof(SomeEnum));
            entityType.GetOrAddProperty("Foo", typeof(string));
            entityType.GetOrAddProperty("Goo", typeof(Guid?));
            entityType.GetOrAddProperty("Id", typeof(int));
            entityType.GetOrAddProperty("MaybeEnum", typeof(SomeEnum?));

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

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

            Assert.Equal(77, entity.Id);
            Assert.Equal("Fu", entity.Foo);
            Assert.Equal(gu, entity.Goo);
            Assert.Equal(SomeEnum.EnumValue, entity.Enum);
            Assert.Null(entity.MaybeEnum);
        }
        public void Throws_if_annotated_field_name_is_not_found()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSide));
            var property = entityType.GetOrAddProperty("SpeakToMe", typeof(int));
            property["BackingField"] = "_speakToMe";

            Assert.Equal(
                Strings.MissingBackingField(typeof(TheDarkSide).FullName, "SpeakToMe", "_speakToMe"),
                Assert.Throws<InvalidOperationException>(
                    () => new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType)).Message);
        }
        public void Property_setter_is_used_if_no_matching_field_is_found()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSide));
            var property = entityType.GetOrAddProperty("OnTheRun", typeof(int));

            var mapping = new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType).Single();

            Assert.Same(property, mapping.Item1);
            Assert.IsAssignableFrom<PropertyInfo>(mapping.Item2);
            Assert.Equal("OnTheRun", mapping.Item2.Name);
        }
        public void Throws_if_annotated_field_if_types_not_compatible()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSide));
            var property = entityType.GetOrAddProperty("SpeakToMe", typeof(int));
            property["BackingField"] = "_badFieldForSpeak";

            Assert.Equal(
                Strings.BadBackingFieldType("_badFieldForSpeak", typeof(string).Name, typeof(TheDarkSide).FullName, "SpeakToMe", typeof(int).Name),
                Assert.Throws<InvalidOperationException>(
                    () => new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType)).Message);
        }
        public void Field_name_match_is_used_in_preference_to_property_setter()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSide));
            var property = entityType.GetOrAddProperty("Breathe", typeof(int));

            var mapping = new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType).Single();

            Assert.Same(property, mapping.Item1);
            Assert.IsAssignableFrom<FieldInfo>(mapping.Item2);
            Assert.Equal("_breathe", mapping.Item2.Name);
        }
        private static void FieldMatchTest(string propertyName, string fieldName)
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSideOfTheMoon));
            var property = entityType.GetOrAddProperty(propertyName, typeof(int));
            var propertyInfo = entityType.ClrType.GetAnyProperty(propertyName);
            var fields = propertyInfo.DeclaringType.GetRuntimeFields().ToDictionary(f => f.Name);

            var matchedField = new FieldMatcher().TryMatchFieldName(property, propertyInfo, fields);

            Assert.Equal(fieldName, matchedField.Name);
        }
        public void Delegate_setter_can_set_value_type_property()
        {
            var entityType = new Model().AddEntityType(typeof(Customer));
            var idProperty = entityType.GetOrAddProperty("Id", typeof(int));

            var customer = new Customer { Id = 7 };

            new ClrPropertySetterSource().GetAccessor(idProperty).SetClrValue(customer, 1);

            Assert.Equal(1, customer.Id);
        }
        public void Delegate_setter_is_cached_by_type_and_property_name()
        {
            var entityType = new Model().AddEntityType(typeof(Customer));
            var idProperty = entityType.GetOrAddProperty("Id", typeof(int));

            var source = new ClrPropertySetterSource();

            var accessor = source.GetAccessor(typeof(Customer), "Id");
            Assert.Same(accessor, source.GetAccessor(typeof(Customer), "Id"));
            Assert.Same(accessor, source.GetAccessor(idProperty));
        }
        public void Adding_a_foreign_key_throws_if_related_entity_is_from_different_model()
        {
            var dependentEntityType = new Model().AddEntityType(typeof(Customer));
            var fkProperty = dependentEntityType.GetOrAddProperty(Customer.IdProperty);
            var principalEntityType = new Model().AddEntityType(typeof(Order));
            var idProperty = principalEntityType.GetOrAddProperty(Order.IdProperty);

            Assert.Equal(
                CoreStrings.EntityTypeModelMismatch(typeof(Customer).FullName, typeof(Order).FullName),
                Assert.Throws<InvalidOperationException>(() => dependentEntityType.AddForeignKey(new[] { fkProperty }, principalEntityType.GetOrAddKey(idProperty), principalEntityType)).Message);
        }
        public void Property_and_field_in_base_type_is_matched()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSide));
            var property = entityType.GetOrAddProperty("TheGreatGigInTheSky", typeof(int));

            var mapping = new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType).Single();

            Assert.Same(property, mapping.Item1);
            Assert.IsAssignableFrom<FieldInfo>(mapping.Item2);
            Assert.Equal("_theGreatGigInTheSky", mapping.Item2.Name);
        }
        public void IsRequired_false_for_composite_FK_by_default()
        {
            var entityType = new Model().AddEntityType("E");
            entityType.GetOrSetPrimaryKey(new[]
            {
                entityType.GetOrAddProperty("Id1", typeof(int), shadowProperty: true),
                entityType.GetOrAddProperty("Id2", typeof(string), shadowProperty: true)
            });

            var dependentProp1 = entityType.GetOrAddProperty("P1", typeof(int), shadowProperty: true);
            var dependentProp2 = entityType.GetOrAddProperty("P2", typeof(string), shadowProperty: true);

            var foreignKey = new ForeignKey(new[] { dependentProp1, dependentProp2 }, entityType.GetPrimaryKey(), entityType);

            Assert.Null(foreignKey.IsRequired);
            Assert.False(((IForeignKey)foreignKey).IsRequired);
        }
        public void Setting_IsRequired_to_false_will_set_all_FK_properties_as_nullable()
        {
            var entityType = new Model().AddEntityType("E");
            entityType.GetOrSetPrimaryKey(new[]
            {
                entityType.GetOrAddProperty("Id1", typeof(int), shadowProperty: true),
                entityType.GetOrAddProperty("Id2", typeof(string), shadowProperty: true)
            });

            var dependentProp1 = entityType.GetOrAddProperty("P1", typeof(int?), shadowProperty: true);
            var dependentProp2 = entityType.GetOrAddProperty("P2", typeof(string), shadowProperty: true);

            var foreignKey = new ForeignKey(new[] { dependentProp1, dependentProp2 }, entityType.GetPrimaryKey(), entityType) { IsRequired = false };

            Assert.False(foreignKey.IsRequired.Value);
            Assert.True(dependentProp1.IsNullable.Value);
            Assert.True(dependentProp2.IsNullable.Value);
        }
        public void IsRequired_and_IsUnique_null_when_dependent_property_nullable_by_default()
        {
            var entityType = new Model().AddEntityType("E");
            entityType.GetOrSetPrimaryKey(entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true));
            var dependentProp = entityType.GetOrAddProperty("P", typeof(int?), shadowProperty: true);

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

            Assert.Null(foreignKey.IsRequired);
            Assert.False(((IForeignKey)foreignKey).IsRequired);
            Assert.Null(foreignKey.IsUnique);
            Assert.False(((IForeignKey)foreignKey).IsUnique);
        }
        public void Private_setter_in_base_class_of_overridden_property_is_used()
        {
            var entityType = new Model().AddEntityType(typeof(TheDarkSide));
            var property = entityType.GetOrAddProperty("UsAndThem", typeof(int));

            var mapping = new MemberMapper(new FieldMatcher()).MapPropertiesToMembers(entityType).Single();

            Assert.Same(property, mapping.Item1);
            Assert.IsAssignableFrom<PropertyInfo>(mapping.Item2);
            Assert.Equal("UsAndThem", mapping.Item2.Name);
        }
        public void IsRequired_false_when_any_part_of_composite_FK_is_nullable()
        {
            var entityType = new Model().AddEntityType("E");
            entityType.GetOrSetPrimaryKey(new[]
            {
                entityType.GetOrAddProperty("Id1", typeof(int), shadowProperty: true),
                entityType.GetOrAddProperty("Id2", typeof(string), shadowProperty: true)
            });

            var dependentProp1 = entityType.GetOrAddProperty("P1", typeof(int), shadowProperty: true);
            var dependentProp2 = entityType.GetOrAddProperty("P2", typeof(string), shadowProperty: true);
            dependentProp2.IsNullable = true;

            var foreignKey = new ForeignKey(new[] { dependentProp1, dependentProp2 }, entityType.GetPrimaryKey(), entityType);

            Assert.Null(foreignKey.IsRequired);
            Assert.False(((IForeignKey)foreignKey).IsRequired);

            dependentProp2.IsNullable = false;

            Assert.Null(foreignKey.IsRequired);
            Assert.True(((IForeignKey)foreignKey).IsRequired);
        }
        public void Delegate_setter_can_set_nullable_enum_property()
        {
            var entityType = new Model().AddEntityType(typeof(Customer));
            var idProperty = entityType.GetOrAddProperty("OptionalFlag", typeof(Flag?));

            var customer = new Customer { Id = 7 };

            new ClrPropertySetterSource().GetAccessor(idProperty).SetClrValue(customer, Flag.Two);

            Assert.Equal(Flag.Two, customer.OptionalFlag);
        }
        public void Fields_flagged_as_null_are_converted_to_nulls()
        {
            var valueReaderMock = new Mock<IValueReader>();
            valueReaderMock.Setup(m => m.ReadValue<int>(2)).Returns(77);
            valueReaderMock.Setup(m => m.ReadValue<string>(0)).Throws(new InvalidCastException("Attempt to cast DBNull value."));
            valueReaderMock.Setup(m => m.ReadValue<Guid?>(1)).Throws(new InvalidCastException("Attempt to cast DBNull value."));
            valueReaderMock.Setup(m => m.IsNull(2)).Returns(false);
            valueReaderMock.Setup(m => m.IsNull(0)).Returns(true);
            valueReaderMock.Setup(m => m.IsNull(1)).Returns(true);

            var entityType = new Model().AddEntityType(typeof(SomeEntity));
            entityType.GetOrAddProperty("Id", typeof(int));
            entityType.GetOrAddProperty("Foo", typeof(string));
            entityType.GetOrAddProperty("Goo", typeof(Guid?));

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

            var entity = (SomeEntity)factory(valueReaderMock.Object);

            Assert.Equal(77, entity.Id);
            Assert.Null(entity.Foo);
            Assert.Null(entity.Goo);
        }
        public void Can_create_materializer_for_entity_ignoring_shadow_fields()
        {
            var entityType = new Model().AddEntityType(typeof(SomeEntity));
            entityType.GetOrAddProperty("Id", typeof(int));
            entityType.GetOrAddProperty("IdShadow", typeof(int), shadowProperty: true);
            entityType.GetOrAddProperty("Foo", typeof(string));
            entityType.GetOrAddProperty("FooShadow", typeof(string), shadowProperty: true);
            entityType.GetOrAddProperty("Goo", typeof(Guid?));
            entityType.GetOrAddProperty("GooShadow", typeof(Guid), shadowProperty: true);

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

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

            Assert.Equal(77, entity.Id);
            Assert.Equal("Fu", entity.Foo);
            Assert.Equal(gu, entity.Goo);
        }
        private ForeignKey CreateSelfRefFK(bool useAltKey = false)
        {
            var entityType = new Model().AddEntityType(typeof(SelfRef));
            var pk = entityType.GetOrSetPrimaryKey(entityType.GetOrAddProperty("Id", typeof(int)));
            var fkProp = entityType.GetOrAddProperty("SelfRefId", typeof(int?));

            var principalKey = useAltKey
                ? entityType.GetOrAddKey(entityType.GetOrAddProperty("AltId", typeof(int), shadowProperty: true))
                : pk;

            var fk = entityType.AddForeignKey(new[] { fkProp }, principalKey, entityType);
            fk.IsUnique = true;
            entityType.AddNavigation("SelfRefPrincipal", fk, pointsToPrincipal: true);
            entityType.AddNavigation("SelfRefDependent", fk, pointsToPrincipal: false);
            return fk;
        }
        public void Delegate_setter_can_set_nullable_property_with_null_value()
        {
            var entityType = new Model().AddEntityType(typeof(Customer));
            var idProperty = entityType.GetOrAddProperty("OptionalInt", typeof(int?));

            var customer = new Customer { Id = 7 };

            new ClrPropertySetterSource().GetAccessor(idProperty).SetClrValue(customer, null);

            Assert.Null(customer.OptionalInt);
        }
        public void IsRequired_true_when_dependent_property_not_nullable()
        {
            var entityType = new Model().AddEntityType("E");
            entityType.GetOrSetPrimaryKey(entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true));
            var dependentProp = entityType.GetOrAddProperty("P", typeof(int), shadowProperty: true);
            dependentProp.IsNullable = false;

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

            Assert.Null(foreignKey.IsRequired);
            Assert.True(((IForeignKey)foreignKey).IsRequired);
        }