实体框架7因创建具有相同名称的导航属性而无法创建迁移

时间:2016-01-21 22:31:19

标签: c# ef-code-first entity-framework-core ef-fluent-api

我正在尝试使用Entity Framework 7创建我的第一次迁移,首先进行代码开发,我收到以下错误:

  

无法将属性“电子邮件”添加到实体类型“UserDTO”   因为已经存在具有相同名称的导航属性   实体类型'UserDTO'。

我的环境是: 1)Visual Studio 2015 2)Entity Framework v7.0.0-rc1-final 3)代码第一次开发 4)使用流畅的API,而不是数据注释

我无法弄清楚问题的根源是什么,但我有一些想法。我的RoleDTO类应该使用其电子邮件地址属性作为其PK,并且它还有一组RoleDTO对象作为属性。

以下是我现在唯一从DbContext继承的课程。我已经注释掉了我必须尝试的另一个实体来减少问题。

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);
    }
}

这是UserDTO类。当我尝试进行迁移时,有人能看到导致错误的原因吗?

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

如果我将UserDTO的密钥切换为普通字符串而不是Complext对象EmailAddress,它看起来好像已经过了那个错误,我得到了一个不同的,同样有趣的:

  

实体类型的属性“角色”   'Microsoft.SRE.NavisionOnline.ConfigurationAutomation.DAL.SQLEntities.UserDTO'   尚未添加到模型中或被忽略。

1 个答案:

答案 0 :(得分:3)

据我所知,你不能使用复杂类型作为PK。

对于第二条错误消息: 您不能使用ICollection<string> Roles {..},EF不会将此属性映射到表,因为您使用“string”作为类型。

您需要定义Role类并为其指定PK

public class Role
{
     public int Id {get; set;}
     public string RoleName {get; set;}
}

然后在你的UserDTO中:

public ICollection<Role> Roles {...}