sql server审计一个表用代码第一个MVC [英] sql server auditing a table with code first MVC

查看:107
本文介绍了sql server审计一个表用代码第一个MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我仍然坚持我一直在努力的审计表。

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

这些是我的模型:

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

这是在我的dbase上下文,以确保用户将有一个必需的配置文件,但配置文件没有必需的用户。

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

在我的种子这是我为我的第一个用户/管理员: / p>

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:


无法确定依赖操作的有效排序
依赖可能由于fk约束,模型要求或
存储生成的值

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

我知道AuditById导致它有1,它仍然不存在保存。有办法解决这个问题吗?或任何建议,如何我应该建模用户和配置文件表?我需要配置文件存在,即使没有用户和用户不能存在没有配置文件。

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.

感谢您的帮助!

推荐答案

然后在创建用户记录时添加对它的引用。

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

    ...
}

这篇关于sql server审计一个表用代码第一个MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆