Reputation: 21166
If I have the following:
class Project
{
...
public virtual IList<URL> URLs {get;set;}
}
class URL
{
...
public virtual Project Project {get;set;}
}
The database created adds ProjectID
to the URLs
database table...
How do I force entity to create the relationship table for me to remove that dependency on URL
without having to declare a new entity called ProjectURL
like so:
public class ProjectURL
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProjectURLID { get; set; }
public URL URL { get; set; }
public Project Project{ get; set; }
}
What I currently have:
Projects
ProjectID |
---------------------
64 |
URLs
URLID | ProjectID |
---------------------
13 | 64
What I want to have:
Projects
ProjectID |
---------------------
64 |
URLs
URLID |
---------------------
13 |
Project_URLs
URLID | ProjectID
---------------------
13 | 64
Upvotes: 0
Views: 37
Reputation: 875
You will need to configure the mapping for your URL entity so that it is splitted into two tables. One table will be the URL, the other will also contain the additional properties (like the foregin key to Project). Take a look at the Map method.
Your mapping configuration will look like:
class URLMap : EntityTypeConfiguration<URL>
{
public URLMap()
{
Map(m =>
{
m.Properties(p => new {p.ID, p.Project});
m.ToTable("Project_URLs");
});
Map(m =>
{
m.Properties(p => new
{
p.ID,
// all other properties separated by ,
});
m.ToTable("URLs");
});
HasKey(p => p.ID);
}
}
Be aware of defining the same primary key for both tables (in the above example I assumed an ID
property).
edit: In cas you don't know what to do with the mapping configuration class.
You have to add an instance of this class to the override of DbContext.OnModelCreating
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new URLMap());
}
Upvotes: 1