I am using a code first migration approach to creating new tables in an existing database, and I'd like to know if this is auto-creating a property-to-field mapping somewhere in the project.
For example: the "Category" table pre-existed in the database. It was created directly in SQL, and my MCV project has a CategoryMap.cs file that explicitly maps the Category entity properties to the Category table fields:
CategoryMap.cs
this.ToTable("Category", "ctt");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.ClientId).HasColumnName("ClientId");
this.Property(t => t.CategoryTypeId).HasColumnName("CategoryTypeId");
etc.
The db context class explicitly points to this mapping in the OnModelCreating method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CategoryMap());
etc.
With this set-up, I can save data to the Category table, as long as I keep the mapping pieces in place.
On the other hand, I've created a new table using the code first approach:
1) Create a "MyTable" entity class
2) Add this code to my context class:
public DbSet<MyTable> MyTable { get; set; }
3) Run the add-migration and update-database commands
That created a "MyTable" table in the database schema, and I can save data to this table, despite the fact that there is no mapping file, and no explicit mapping code in the OnModelCreating method of my db context class.
Now, if I comment out the "modelBuilder.Configurations.Add(new CategoryMap());" line of code in the context class, I can't save data to that table any more; I get a "table 'Category' not found" error message when I try to do db.SaveChanges().
So I guess my question is this: when I created "MyTable" using the add-migration and update-database commands, did a class-to-table map get auto-generated somewhere behind the scenes? If so, can I access it and view it?
There are no auto generated mappings as such but a number of mapping conventions that get applied if there are no specific mappings. For example if you have no explicit table mapping then by convention it will map to a table that matches the class name.
So for a class Category it will by convention map to a table called Category.
This is also true of properties so Property(t => t.Id).HasColumnName("Id"); doesn't actually do anything as the property will have that mapping by convention. You only need explicit mappings when you go outside the conventions. So if you wanted to map you property Id to a column called Category_id then you would need a column mapping Property(t => t.Id).HasColumnName("Category_id");
Read this MSDN article for more info on the default conventions.
Related
As a newcomer to EF migrations, I was surprised by the following behaviour, and wondered if it's intentional (i.e. there's a switch to make it go away).
When I rename a column, I have the following relevant lines inside an EntityTypeConfiguration class:
Property(x => x.MyColumn).HasColumnName(#"MyColumn").HasColumnType("nvarchar").IsOptional();
And, crucially:
HasOptional(a => a.RelatedTable).WithMany(b => b.ThisTable).HasForeignKey(c => c.MyColumn).WillCascadeOnDelete(false);
Which is, as I understand it, establishing a foreign key relationship. When I rename MyColumn to MyColumn2, the migration that is created looks like this:
public override void Up()
{
RenameColumn(table: "dbo.ThisTable", name: "MyColumn", newName: "MyColumn2");
RenameIndex(table: "dbo.ThisTable", name: "IX_MyColumn", newName: "IX_MyColumn2");
}
However, MyColumn is not indexed on ThisTable. I realise that creating indexes for a foreign key relationship is advisable; is this why EF assumes there is one?
Note that the EF model was generated from the DB initially using the EF Reverse POCO Generator.
It's intentional. Code First migrations are based purely on model (data annotations, fluent configuration) and assume the previous database state is created using migration as well. Since EF default convention is to create index for FK columns, the migration assumes that the index exists and tries to rename it.
You can solve it in two ways. Either edit the generated migration and remove the RenameIndex (and other index related commands), or turn off (remove) the default FK index convention:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<ForeignKeyIndexConvention>();
// ...
}
Please note that the later will affect your future model modifications and you have to explicitly opt for index on FK columns (which cannot be done if the entity does not have explicit FK property). Also if you rename some of the exiting FK columns which do have an index, you'll have to add RenameIndex (or DropIndex/CreateIndex`) commands manually.
I'm trying to implement TPH inheritance with Entity Framework 6 Code First and am having problems with a relationship from my inherited types.
My code is
public abstract class Base...
public class Inherited1 : Base
{
public virtual Type1 Rel { get; set; }
...
public class Inherited2 : Base
{
public virtual Type1 Rel {get;set;}
...
So the inherited types have the "same" relationship. The inheritance itself works fine, but the problem I'm having is that the relationship to the table Type1 will be added twice (logical...) and the other relationship is from Inherited2.Id to Type1.Id instead of Inherited2.Type1Id to Type1.Id that the first relationship is (correctly).
I'm not sure if I made any sense explaining this and with the partial code sample with changed type names, but I hope you got the point. Ask for more details if you need any.
I probably could implement this correctly with
UPDATE
I've created a sample Github repo to demonstrate the issue. Feel free to tell me what I'm doing wrong. https://github.com/antsim/EntityFrameworkTester
Try to use the following
1- if you want TPT
modelBuilder.Entity<Inherited1>()
.ToTable("Inherited1s")
.HasKey(x => x.YourKey)
.HasRequired(x=>Type1)
.WithMany()
.HasForeignKey(x=>Type1Id)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Inherited2>()
.ToTable("Inherited2s")
.HasKey(x => x.YourKey)
.HasRequired(x=>Type1)
.WithMany()
.HasForeignKey(x=>Type1Id)
.WillCascadeOnDelete(false);
2 - if you want TPH
modelBuilder.Entity<Base>()
.ToTable("YourTableName")
.HasRequired(m=>m.Type1)
.WithMany()
.HasForeignKey(m=>m.Type1Id)
.WillCascadeOnDelete(); // true or false as you want
for more details you might check this article
based on the sample you provided
Attachment and Document are inherited from File and you are using TPH which means One table will be created with a Discriminator field.
Document and FileContainer has a relation of type 0..1 which means a Foreign Key FileContainerId should be created in the Document hence in the File table
FileContainer and Attachment has a relation of type 0..n, then another nullable foreign key will be created in the table File
in the example you provided, I made the following changes
Add FileContainerId to the table Document
Add FileContainerAttachmentId to the table Attachment
The changes made on the TestContext was
modelBuilder.Entity<FileContainer>()
.HasOptional(x => x.Document)
.WithMany()
.HasForeignKey(t => t.DocumentId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Document>()
.HasRequired(t => t.FileContainer)
.WithMany()
.HasForeignKey(t => t.FileContainerId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Attachment>()
.HasRequired(t => t.FileContainer)
.WithMany()
.HasForeignKey(t => t.FileContainerAttachmentId)
.WillCascadeOnDelete(false);
the output was correct ( File table contains discriminator field in addition to two relations one for the document with the container and the other for the attachment with the container).
A better solution in my opinion is:
To add a class FileType ( Id, Name) with values Attachment, Document, and add it as a foreign key in File
To add only one relation 0..n between the FileContainer and File
To validate that only one record in the File of type document to same container
Hope this will help you
I have my database with table names starting with "tbl" prefix and column names like "ua_id" which are understandable in context of project but problematic if used in a model i.e names should be readable or meaningful(not like indicative names defined in database).
So I want to map them in my onmodelcreating method but I have no idea about it. I studied it in following blog:
http://weblogs.asp.net/scottgu/entity-framework-4-code-first-custom-database-schema-mapping
but this is for EF 4.1 and method doesn't work for EF 6.(mapsingletype method)
I want to map my tables by columns to my model as I can't change the column names. I just want the newer version of that syntax in the blog.
Thank You.
If you are using Code First, you can simply decorate your model with Table and Column attribute and give it the database names.
[Table("tbl_Student")]
public class Student
{
[Column("u_id")]
public int ID { get; set; }
}
These attributes are available in the System.ComponentModel.DataAnnotations.Schema namespace
You can keep following inside OnModelCreating
modelBuilder.Entity<MyModel>()
.Property(e => e.MyColumn).HasColumnName("DBColumn")
And if you're not using code-first, just select a table in the model diagram, hit F4 (properties) and change the name.
Am I able to use Entity Framework models (Classes) as a classes for asp.net Identity
so the relations that I have in my database will be loaded when I retrieve the user and if I update any columns or add tables I only have to deal with Entity Framework model.
I did do my custom classes for users
public class MyUser : IdentityUser<long, MyLogin, MyUserRole, MyClaim>{ ... }
and connected it with the table
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyUser>().ToTable("Users");
.....
}
but I have more tables that are connected with 'Users' table that isn't with Identity model
for example:
I have a table called Person(Not really just an example)
and each person may have many users and each user may have many
persons
So We have another table called 'PersonsUsers'
So the user have a list
I don't want to call the database twice to retrieve a single user data, and mapping the table from code will make my code static and depends on me updating the source code.
so Is it possible to use the classes that EF generated for the tables?
Do you have any other solution?
Yes, this is possible. Your MyUser class could have a property with the list of Person. then in your modelBuilder, you set up the mappings. Something like this:
modelBuilder.Entity<MyUser>().HasMany(m => m.Person)
.WithMany(p => p.MyUser)
.Map(m => {
m.ToTable("PersonUsers");
m.MapLeftKey("MyUserID");
m.MapRightKey("PersonID");
I believe this will accomplish what you're looking for.
I have the following model-first (is that what it's called?) diagram that I have made. I use T4 to generate the classes.
Now, I have a problem that causes Entity Framework to somehow append a "1" to the table name of the DatabaseSupporter entity. The database has been generated from this very model, and nothing has been modified.
I am trying to execute the following line:
_entities.DatabaseSupporters.SingleOrDefault(s => s.Id == myId);
The error I receive when executing that line (along with its inner exception below) is:
An exception of type
'System.Data.Entity.Core.EntityCommandExecutionException' occurred in
mscorlib.dll but was not handled in user code.
Invalid object name 'dbo.DatabaseSupporter1'.
I tried fixing the problem with the following Fluent API code (notice the second line in the function that names the table explicitly to "DatabaseSupporter"), but with no luck.
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder
.Entity<DatabaseSupporter>()
.HasOptional(f => f.DatabaseChatSession)
.WithOptionalPrincipal(s => s.DatabaseSupporter);
modelBuilder
.Entity<DatabaseSupporter>()
.Map(m =>
{
m.Property(s => s.Id)
.HasColumnName("Id");
m.ToTable("DatabaseSupporter");
});
modelBuilder
.Entity<DatabaseSupporter>()
.HasMany(s => s.DatabaseGroups)
.WithMany(g => g.DatabaseSupporters)
.Map(m =>
{
m.ToTable("DatabaseSupporterDatabaseGroup");
m.MapLeftKey("DatabaseGroups_Id");
m.MapRightKey("DatabaseSupporters_Id");
});
modelBuilder
.Entity<DatabaseGroup>()
.HasRequired(g => g.DatabaseChatProgram)
.WithMany(c => c.DatabaseGroups);
modelBuilder
.Entity<DatabaseGroup>()
.HasRequired(g => g.DatabaseOwner)
.WithMany(o => o.DatabaseGroups);
modelBuilder
.Entity<DatabaseOwner>()
.HasMany(o => o.DatabaseChatSessions)
.WithRequired(o => o.DatabaseOwner);
base.OnModelCreating(modelBuilder);
}
It should be mentioned that the Id property for every entity actually is a Guid.
I am using Entity Framework 6.0.2.
Any ideas?
Edit 1
Here's the generated DatabaseSupporter.cs file containing my DatabaseSupporter entity as requested in the comments.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Coengage.Data.Entities
{
using System;
using System.Collections.Generic;
public partial class DatabaseSupporter
{
public DatabaseSupporter()
{
this.DatabaseGroups = new HashSet<DatabaseGroup>();
}
public bool IsActive { get; set; }
public string Username { get; set; }
public System.Guid Id { get; set; }
public virtual DatabaseChatSession DatabaseChatSession { get; set; }
public virtual ICollection<DatabaseGroup> DatabaseGroups { get; set; }
}
}
Edit 2
The errors started occuring after I added the many-to-many link between DatabaseSupporter and DatabaseGroup. Before that link, the Fluent code wasn't needed either.
This mapping is incorrect:
modelBuilder
.Entity<DatabaseSupporter>()
.Map(m =>
{
m.Property(s => s.Id)
.HasColumnName("Id");
m.ToTable("DatabaseSupporter");
});
It is kind of 50 percent of a mapping for Entity Splitting - a mapping that stores properties of a single entity in two (or even more) separate tables that are linked by one-to-one relationships in the database. Because the mapping is not complete you even don't get a correct mapping for Entity Splitting. Especially EF seems to assume that the second table that contains the other properties (that are not explicitly configured in the mapping fragment) should have the name DatabaseSupporter1. I could reproduce that with EF 6 (which by the way has added a Property method to configure single properties in a mapping fragment. In earlier versions that method didn't exist (only the Properties method).) Also the one-to-one constraints are not created correctly in the database. In my opinion EF should throw an exception about an incorrect mapping here rather than silently mapping the model to nonsense without exception.
Anyway, you probably don't want to split your entity properties over multiple tables but map it to a single table. You must then replace the code block above by:
modelBuilder.Entity<DatabaseSupporter>()
.Property(s => s.Id)
.HasColumnName("Id");
modelBuilder.Entity<DatabaseSupporter>()
.ToTable("DatabaseSupporter");
The first mapping seems redundant because the property Id will be mapped by default to a column with the same name. The second mapping is possibly also redundant (depending on if table name pluralization is turned on or not). You can try it without this mapping. In any case you shouldn't get an exception anymore that complains about a missing dbo.DatabaseSupporter1.
I have replicated your model exactly as you have listed it and I cannot currently reproduce your issue in the DDL that the EDMX surface emits when Generating Database from Model.
Could you please provide detailed information on exactly how you are going about adding your many-to-many relationship between DatabaseGroup and DatabaseSupporter? You say that you're trying to add the relationship on the edmx surface and NOT through code and it craps on your table name?
I added this thing Many-to-many from DatabaseGroup to DatabaseSupporter
I added this thing Many-to-many from DatabaseSupporter to DatabaseGroup
Can you please provide the following:
Rollback to your codebase prior to adding the many-to-many relationship. Ensure that your EF Fluent API code is not currently in your project.
Generate the DDL from this surface and confirm that it is not being
generated with the name DatabaseSupporters1 (Post the tablename that
it chooses at this stage. DatabaseSupporter or DatabaseSupporters)
Now, right click DatabaseGroup| Add New| Association
Choose DatabaseGroup for the left and DatabaseSupporter for the
right. Confirm that the name of the association that the designer
chooses is DatabaseGroupDatabaseSupporter [Do not create]
Choose DatabaseSupporter for the left and DatabaseGroup for the
right. Confirm that the name of the association that the designer
chooses is DatabaseSupporterDatabaseGroup [Create]
From the edmx surface, right click the many-to-many association just created and click "Show in Model Browser"
Edit your post to include the settings that display.
Also, right click the surface and click "Generate Database from Model."
Edit your post to include the DDL that gets generated. The table
should be named [DatabaseSupporters]
(My first inclination is that it's going to have something to do with your navigation properties, but not entirely sure. I actually had Entity Framework do the same thing to me in a toy project I was working on but I recall it being trivial to correct and I don't recall what the root cause was; I seem to recall it being something about the nav properties)
[Edit]
Wait.....
If I remove the many-to-many that doesn't fix my problem. However,
reverting to before I added the many-to-many fixes it. The exact code
that throws the exception is already shown. If I remove my fluent
mappings entirely, it's not the same exception being thrown (it throws
something about a group and a supporter, and a principal). I have not
tried recreating the model in an empty project - that takes a lot of
time. I already tried searching the EDMX in Notepad for references -
none were found.
(note my added emphasis)
So the DatabaseSupporter1 error showed up after you tried your fluent api patch? Get rid of the patch, add the many-to-many and give us the real error then.
...also, it took me 5 minutes to build this diagram. I wouldn't qualify that as "a lot of time."
I don't have my dev environment here in front of me, but my immediate thoughts are:
FIRST
Your fluent looks ok - but is the plural s in your ID column correct? And no plural (s) on the table names? This would be the opposite of convention.
SECOND
EF will automatically append a number to address a name collision. See similar question here: Why does EntityFramework append a 1 by default in edmx after the database entities?
Any chance you have something hanging around - a code file removed from your solution but still in your build path? Have you tried searching your source folder using windows explorer rather than the visual studio?
modelBuilder
.Entity<DatabaseSupporter>()
.HasMany(s => s.DatabaseGroups)
.WithMany(g => g.DatabaseSupporters)
.Map(m =>
{
m.ToTable("DatabaseSupporterDatabaseGroup");
m.MapLeftKey("DatabaseGroups_Id");
m.MapRightKey("DatabaseSupporters_Id");
});
Left and Right are inversed on Many to Many.
Try this :
modelBuilder
.Entity<DatabaseSupporter>()
.HasMany(s => s.DatabaseGroups)
.WithMany(g => g.DatabaseSupporters)
.Map(m =>
{
m.ToTable("DatabaseSupporterDatabaseGroup");
m.MapLeftKey("DatabaseSupporters_Id");
m.MapRightKey("DatabaseGroups_Id");
});
I think the DatabaseSupporter class created two time
one name is : DatabaseSupporter
another one is : DatabaseSupporter1
The modified changes are stored in DatabaseSupporter1 and mapping to here.
You need to copy the DatabaseSupporter1 class code and past the code to DatabaseSupporter class . then delete this DatabaseSupporter1 class.
I had this issue from renaming tables in the diagram, specifically changing just the capitalization.
If you rename a table by clicking on the header in the diagram, I think it checks the entity set name before trying to change it, sees it exists (even though it's the same entity set), and appends a 1.
However, if you right-click and open the Properties pane and first rename the Entity Set Name, then change the Name second, it won't add the number.
In my case i have two tables in the same database with the same name (2 different schemas(see image)