问题
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!
回答1:
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; }
...
}
来源:https://stackoverflow.com/questions/11033935/sql-server-auditing-a-table-with-code-first-mvc