1
votes

I pass the ASP.NET MVC 5 tutorial and want to rewrite existing app to mvc 5. Let's say I have 2 tables - Users and Categories and they are connect on UserID.

In mvc5 we can connect authentification model to our db, so I updated sample User model with

public ICollection<Category> Categories { get; set; }

also in Category model I added

public int UserID { get; set; }
public User User { get; set; }

I worked for me in mvc3/ef4. But when I do migration I am getting error:

The object 'PK_dbo.User' is dependent on column 'Id'. ALTER TABLE ALTER COLUMN Id failed because one or more objects access this column.

Here are my models:

User (1 to 1 from sample project + link to categories)

public class User : IUser
{
    public User()
        : this(String.Empty)
    {
    }

    public User(string userName)
    {
        UserName = userName;
        Id = Guid.NewGuid().ToString();
    }

    [Key]
    public string Id { get; set; }

    public string UserName { get; set; }

    public ICollection<Category> Categories { get; set; }
}

Category model

public class Category
{
    public int UserID { get; set; }
    public User User { get; set; }

    public int ID { get; set; }

    public int ParentID { get; set; }

    public string Name { get; set; }
    //....
}

context

public class BackendDBContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<UserSecret> Secrets { get; set; }
    public DbSet<UserLogin> UserLogins { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }
    public DbSet<Category> Categories { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

    protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
    {
       //
    }
}
1
If a user's Id property is a string, how will you be able to refer to it with an int UserID property in a different class?user743382
i am idiot! thank you!Oleg Kalyta
please add it as answer, so i be able to accept itOleg Kalyta

1 Answers

3
votes

Elaborating from the comments:

Your User class has a string key property. The category's UserID property needs to have the same type. Since they're not, I'm guessing that EF is attempting to modify the ID column to match UserID's type, which is not supposed to work.

However, an added note:

You are setting your user IDs via

Id = Guid.NewGuid().ToString();

but the natural type for storing that is Guid (uniqueidentifier in SQL Server). You could change both the user's ID property and the category's UserID property to that.