I'm trying to create my first migration using Entity Framework 7 with code first development and I'm getting the following error:
The property 'Email' cannot be added to the entity type 'UserDTO' because a navigation property with the same name already exists on entity type 'UserDTO'.
My environment is: 1) Visual Studio 2015 2) Entity Framework v7.0.0-rc1-final 3) Code first development 4) Using the fluent API, not data annotations
I can't figure out what the root cause of the issue is but I've got a few ideas. My RoleDTO class is supposed to use its email address property as its PK, and it also has a collection of RoleDTO objects as a property.
Below is the only class I have inheriting from DbContext right now. I've commented out the other entity I have to try and reduce the problem.
class StorageContext : DbContext
{
public DbSet<UserDTO> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("MySQLServerConnectionString")
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserDTO>().HasKey(entity => entity.Email);
//modelBuilder.Entity<UserDTO>().HasMany(entity => entity.Roles);
}
}
And here is the UserDTO class. Can anyone see what's causing the error when I'm trying to make the migration?
internal class UserDTO
{
public EmailAddress Email { get; private set; }
public string FullName { get; private set; }
public string UserName { get; private set; }
public virtual ICollection<string> Roles { get; private set; }
// more below here like a constructor and some basic methods
If I switch the key for UserDTO to a plain string instead of the complext object EmailAddress it looks like it gets past that error and I get a different, equally interesting one:
The property 'Roles' on entity type 'Microsoft.SRE.NavisionOnline.ConfigurationAutomation.DAL.SQLEntities.UserDTO' has not been added to the model or ignored.
As far as I know you can't use complex type as PK.
For the second error message:
You can't use ICollection<string> Roles {..}
, EF won't map this property to a table because you are using "string" as type.
You need to define Role class and assign it a PK
public class Role
{
public int Id {get; set;}
public string RoleName {get; set;}
}
And then in your UserDTO:
public ICollection<Role> Roles {...}