Create Model From Another Controller

216 views Asked by At

I have a complex user type (more info) which may contain different information based on different types. Now, when I want to register the user, I want to add the necessary information in other database tables. Currently I'm trying to do this:

Models:

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

    //....

    [Required]
    public virtual User User { get; set; }
}

Controller

                if (await Users.Create(user) && await Secrets.Create(new UserSecret(model.UserName, model.Password)) &&
                    await Logins.Add(new UserLogin(user.Id, IdentityConfig.LocalLoginProvider, model.UserName)))
                {
                    var normaluser = new NormalUser(model) { User = user };
                    db.NormalUsers.Add(normaluser);
                    db.SaveChanges();
                    //....

However, when I run this, I get 2 errors on the last line. One error is saying that the Id field of the normaluser should be unique and the other is saying that the User field should be unique. They are both required criteria, but I thought the first is handled by auto-increment of the Id field and I didn't expect the second one since I just created the User.

Am I even doing the right thing by using this method?

Update:

Fixed the first one by changing the type of the Id field from string to int

1

There are 1 answers

0
Alireza Noori On

Well, found my answer. First I had to change the type of the Id field from string to int to enable auto-increment.

And second, I used the newly created User object by mistake. I had to load the info from database:

var newUser = db.Users.Where(u => u.UserName == user.UserName).FirstOrDefault();
var normaluser = new NormalUser(model) { User = newUser };