sql server auditing a table with code first MVC

So I'm still stuck with the audit table that I've been working on.

these are my models:

public interface Audit {
 int AuditById {get;set;}
 DateTime AuditOn {get;set;}

 User AuditBy {get;set;}
}
User {
 Id {get;set;}
 Email {get;set;}
 Password {get;set;}
}
Profile : Audit {
 public int Id {get;set;}
 public string Name {get;set;}
 public int AuditById {get;set;}
 public DateTime AuditOn {get;set;}

 public User AuditBy {get;set;}
 public User User {get;set;}
}

this is on my dbase context to make sure that the User will have a required profile but a profile does not have a required user.

Dbase: DbContext{
   modelbuilder.Entity<Profile>()
    .hasoptional(e => e.User)
    .withrequired(u => u.Profile);
}

On my seed this is what I do for my first user / admin:

var admin = new User{
   Id = 1, 
   Email = 'email@email.com',
   Password = 'woop',
   Profile = new Profile {
           Name = 'admin name',
           AuditById = 1,
          AuditOne = DateTime.Now
   }
}

So, I'm getting this error:

"Unable to determine a valid ordering for dependent operations. Dependencies may exist due to fk constraints, model requirements, or store generated values"

I understand that the AuditById is causing this having it to be 1 which still doesn't exist on Save. Is there a way to work around this? Or any advice on how I should model the user and Profile tables? I need the Profile to exist even without the User and the User can't exist without a Profile.

Appreciate your help thanks!

Answers


Try creating the Profile record first and then adding a reference to it when you create the User record.

dbContext.Profiles.Add(new Profile { Id = 1, ... });

var admin = new User{
   Id = 1, 
   Email = 'email@email.com',
   Password = 'woop',
   ProfileId = 1
   }
}

dbContext.Users.Add(admin);

dbContext.SaveChanges();

Also, I'm assuming the code you included in your question is psuedo-code, if not you're probably missing some important things (like navigation properties), perhaps the below will help:

class User 
{
    [Key]
    protected int Id { get; set; }

    [ForeignKey("Profile")]
    protected int ProfileId { get; set; }

    protected Profile Profile { get; set; }

    ...

}

class Profile
{
    [Key]
    protected int Id { get; set; }

    [ForeignKey("User")]
    protected int? UserId { get; set; }

    protected User User { get; set; }

    ...
}

Need Your Help

How to set ListView selected item alternet text color in android

android android-listview

I have a custom listview with a imageview and an textview. I want when user select a item the textview color should change and all the other textview should remain default.

Confused about the ordering of results

solr

I am using Adobe AEM V5.6 with Solr V4.2 and I have a question about the results ranking