private void ConfigureFunctionMappings( EdmModel model, EntityTypeConfiguration entityTypeConfiguration, EntityType entityType) { if (entityTypeConfiguration.ModificationStoredProceduresConfiguration == null) { return; } for (; entityType.BaseType != null; entityType = (EntityType)entityType.BaseType) { Type clrType = EntityTypeExtensions.GetClrType((EntityType)entityType.BaseType); EntityTypeConfiguration typeConfiguration; if (!entityType.BaseType.Abstract && (!this._entityConfigurations.TryGetValue(clrType, out typeConfiguration) || typeConfiguration.ModificationStoredProceduresConfiguration == null)) { throw Error.BaseTypeNotMappedToFunctions((object)clrType.Name, (object)entityTypeConfiguration.ClrType.Name); } } model.GetSelfAndAllDerivedTypes(entityType).Each <EntityType>((Action <EntityType>)(e => { EntityTypeConfiguration typeConfiguration = this.Entity(EntityTypeExtensions.GetClrType(e)); if (typeConfiguration.ModificationStoredProceduresConfiguration != null) { return; } typeConfiguration.MapToStoredProcedures(); })); }
static void ConfigureContinent(EntityTypeConfiguration <Continent> entity) { entity.Property(p => p.Name).IsUnicode(false).HasMaxLength(100); entity.HasIndex(e => e.Name); entity.Property(e => e.Name).IsConcurrencyToken(); entity .HasMany(c => c.Countries) .WithOptional(c => c.Continent) .HasForeignKey(c => c.ContinentId) .WillCascadeOnDelete(true); entity.MapToStoredProcedures(); }
static void ConfigureCity(EntityTypeConfiguration <City> entity) { entity.Property(p => p.Name) .IsUnicode(false) .HasMaxLength(100) .IsConcurrencyToken(); entity.HasIndex(e => e.Name); entity.Property(e => e.Name).IsConcurrencyToken(); entity .HasOptional(c => c.Province) .WithMany(p => p.Cities); entity .HasOptional(c => c.Country); entity.MapToStoredProcedures(); }
public void Generate_should_not_generate_modification_function_mappings_when_entity_abstract() { var model = new EdmModel(DataSpace.CSpace); var entityType = model.AddEntityType("E"); entityType.Abstract = true; entityType.Annotations.SetClrType(typeof(string)); model.AddEntitySet("ESet", entityType); var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object)); entityTypeConfiguration.MapToStoredProcedures(); entityType.SetConfiguration(entityTypeConfiguration); var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(model); Assert.Equal(0, databaseMapping.Database.Functions.Count()); }
public void Generate_should_not_generate_modification_function_mappings_when_entity_abstract() { var model = new EdmModel(DataSpace.CSpace); var entityType = model.AddEntityType("E"); entityType.Abstract = true; entityType.GetMetadataProperties().SetClrType(typeof(string)); var derivedType = model.AddEntityType("D"); derivedType.BaseType = entityType; derivedType.GetMetadataProperties().SetClrType(typeof(object)); model.AddEntitySet("ESet", entityType); var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object)); entityTypeConfiguration.MapToStoredProcedures(); entityType.SetConfiguration(entityTypeConfiguration); var databaseMapping = CreateDatabaseMappingGenerator().Generate(model); Assert.Equal(0, databaseMapping.Database.Functions.Count()); }
public void Can_generate_function_mappings_for_many_to_many_association_set_mapping() { var databaseMapping = new DbDatabaseMapping() .Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace)); var entityType1 = databaseMapping.Model.AddEntityType("E1"); entityType1.Annotations.SetClrType(typeof(string)); databaseMapping.Model.AddEntitySet("E1Set", entityType1); var entityType2 = databaseMapping.Model.AddEntityType("E2"); entityType2.Annotations.SetClrType(typeof(string)); databaseMapping.Model.AddEntitySet("E2Set", entityType2); var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object)); entityTypeConfiguration.MapToStoredProcedures(); entityType1.SetConfiguration(entityTypeConfiguration); entityType2.SetConfiguration(entityTypeConfiguration); var associationSet = databaseMapping.Model.AddAssociationSet( "M2MSet", databaseMapping.Model.AddAssociationType( "M2M", entityType1, RelationshipMultiplicity.Many, entityType2, RelationshipMultiplicity.Many)); var entitySet = new EntitySet("ES", "S", null, null, new EntityType("E", "N", DataSpace.CSpace)); var associationEndMember1 = new AssociationEndMember("Source", new EntityType("E", "N", DataSpace.CSpace)); associationSet.AddAssociationSetEnd(new AssociationSetEnd(entitySet, associationSet, associationEndMember1)); var associationEndMember2 = new AssociationEndMember("Target", new EntityType("E", "N", DataSpace.CSpace)); associationSet.AddAssociationSetEnd(new AssociationSetEnd(entitySet, associationSet, associationEndMember2)); var associationSetMapping = new StorageAssociationSetMapping( associationSet, entitySet) { SourceEndMapping = new StorageEndPropertyMapping() { EndMember = associationEndMember1 }, TargetEndMapping = new StorageEndPropertyMapping() { EndMember = associationEndMember2 } }; associationSetMapping.SourceEndMapping .AddProperty(new StorageScalarPropertyMapping(new EdmProperty("PK"), new EdmProperty("FooId"))); associationSetMapping.TargetEndMapping .AddProperty(new StorageScalarPropertyMapping(new EdmProperty("PK"), new EdmProperty("BarId"))); var functionMappingGenerator = new ModificationFunctionMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest); functionMappingGenerator.Generate(associationSetMapping, databaseMapping); var modificationFunctionMapping = associationSetMapping.ModificationFunctionMapping; Assert.NotNull(modificationFunctionMapping); var functionMapping = modificationFunctionMapping.InsertFunctionMapping; Assert.NotNull(functionMapping); Assert.Equal(2, functionMapping.ParameterBindings.Count); Assert.Null(functionMapping.ResultBindings); var function = functionMapping.Function; Assert.NotNull(function); Assert.Equal("E1E2_Insert", function.Name); Assert.Equal(2, function.Parameters.Count); functionMapping = modificationFunctionMapping.DeleteFunctionMapping; Assert.NotNull(functionMapping); Assert.Equal(2, functionMapping.ParameterBindings.Count); Assert.Null(functionMapping.ResultBindings); function = modificationFunctionMapping.DeleteFunctionMapping.Function; Assert.NotNull(function); Assert.Equal("E1E2_Delete", function.Name); Assert.Equal(2, function.Parameters.Count); }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { //Configure domain classes using Fluent API here . Code-First gives precedence to Fluent API > data annotations > default conventions. //DbModelBuilder class includes important properties and methods to configure //modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.HasDefaultSchema("CF"); //EntityTypeConfiguration Class obtained by calling the Entity<TEntity>() method of DbModelBuilder class EntityTypeConfiguration <CFStudent> SEConfig = modelBuilder.Entity <CFStudent>(); EntityTypeConfiguration <CFStandard> StdEConfig = modelBuilder.Entity <CFStandard>(); // EntityTypeConfiguration Class Fluent API methods - http://www.entityframeworktutorial.net/code-first/entitytypeconfiguration-class.aspx //Configure Table SEConfig.ToTable("Student", "CF"); SEConfig.Map(m =>// Map single entity to multiple table/Split table { m.Properties(p => new { p.StudentID, p.StudentName }); m.ToTable("StudentInfo"); }).Map(m => { m.Properties(p => new { p.StudentID, p.Height, p.Weight, p.Photo, p.DateOfBirth }); m.ToTable("StudentInfoDetail"); }); StdEConfig.ToTable("StandardInfo"); //Configure properties SEConfig.HasKey <int>(s => s.StudentID); //PK StdEConfig.HasKey <int>(s => s.StandardId); SEConfig.HasKey(s => new { s.StudentID, s.StudentName }); //Composite PK SEConfig.Property(p => p.DateOfBirth) // property definition .HasColumnName("DoB") .HasColumnOrder(3) .HasColumnType("datetime2") .IsOptional() //NULL .IsRequired(); //NOT NULL SEConfig.Property(p => p.Height) .HasPrecision(2, 2); SEConfig.Property(p => p.StudentName) .HasMaxLength(50) //Lenghth .IsConcurrencyToken(); //Concurrency Column .can also use IsRowVersion() method for byte[] property to make it as a concurrency column //Below methods are required for making relation between 2 table // .Has[required/optional] .With[required/many] ////One to One ////modelBuilder.Entity<Student>() //// .HasOptional(s => s.Address) // Mark Address property optional in Student entity //// .WithRequired(ad => ad.Student); // mark Student property as required in StudentAddress entity. Cannot save StudentAddress without Student //// Configure StudentId as PK for StudentAddress //modelBuilder.Entity<StudentAddress>() // .HasKey(e => e.StudentId); //// Configure StudentId as FK for StudentAddress //modelBuilder.Entity<Student>() // .HasOptional(s => s.Address) // .WithRequired(ad => ad.StudentId); ////one-to-many //modelBuilder.Entity<Student>() // .HasRequired<Standard>(s => s.Standard) // Student entity requires Standard // .WithMany(s => s.Students); // Standard entity includes many Students entities //modelBuilder.Entity<Student>() // .HasRequired<Standard>(s => s.Standard) // .WithMany(s => s.Students) // .HasForeignKey(s => s.StdId); //modelBuilder.Entity<Standard>() // .HasMany<Student>(s => s.Students) Standard has many Students // .WithRequired(s => s.Standard) Student require one Standard // .HasForeignKey(s => s.StdId); Student includes specified foreignkey property name for Standard ////Nullable foreign key for one-to-many relationship. // modelBuilder.Entity<Student>() // .HasOptional<Standard>(s => s.Standard) // .WithMany(s => s.Students) // .HasForeignKey(s => s.StdId); //Many to Many relationship- http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx //modelBuilder.Entity<Student>() //.HasMany<Course>(s => s.Courses) //.WithMany(c => c.Students) //.Map(cs => //{ // cs.MapLeftKey("StudentRefId"); // cs.MapRightKey("CourseRefId"); // cs.ToTable("StudentCourse"); //}); //BydefaultCascade delte is enabled in Entity Framework, we can turn off by Fluent API //modelBuilder.Entity<Student>() //.HasOptional<Standard>(s => s.Standard) //.WithMany() //.WillCascadeOnDelete(false); //We can move all Student related configuration to StudentEntityConfiguration class modelBuilder.Configurations.Add(new StudentEntityConfiguration()); //CodeFirst SPROC //Automatically creates a stored procedure for Student entity using Fluent API. SEConfig.MapToStoredProcedures(); //Can also change the stored procedure and parameter names SEConfig.MapToStoredProcedures(p => p.Insert(sp => sp.HasName("sp_InsertStudent").Parameter(pm => pm.StudentName, "name").Result(rs => rs.StudentID, "Student_ID")) .Update(sp => sp.HasName("sp_UpdateStudent").Parameter(pm => pm.StudentName, "name")) .Delete(sp => sp.HasName("sp_DeleteStudent").Parameter(pm => pm.StudentID, "Id")) ); //If you want all your entities to use stored procedures //SEConfig.Types().Configure(t => t.MapToStoredProcedures()); //base.OnModelCreating(modelBuilder); //For catching Entity model errors // try // { // var user = model.GetUser(); // var result = await UserManager.CreateAsync(user, model.Password); // } // catch (DbEntityValidationException dbEx) // { // foreach (var validationErrors in dbEx.EntityValidationErrors) // { // foreach (var validationError in validationErrors.ValidationErrors) // { // Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); // } // } // } }