【问题标题】:sql server auditing a table with code first MVCsql server 使用代码优先 MVC 审核表
【发布时间】:2012-06-14 13:18:04
【问题描述】:

所以我仍然坚持使用我一直在处理的审计表。

这些是我的模型:

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 上下文中,以确保用户将具有所需的配置文件,但配置文件没有所需的用户。

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

在我的种子上,这是我为我的第一个用户/管理员所做的:

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

所以,我收到了这个错误:

“无法确定相关操作的有效顺序。 由于 fk 约束、模型要求或 存储生成的值”

我了解 AuditById 导致它为 1,但保存时仍不存在。有没有办法解决这个问题?或者关于我应该如何为用户和配置文件表建模的任何建议?即使没有用户,我也需要配置文件存在,而没有配置文件,用户就无法存在。

感谢您的帮助,谢谢!

【问题讨论】:

    标签: database entity-framework database-design ef-code-first


    【解决方案1】:

    尝试先创建个人资料记录,然后在创建用户记录时添加对它的引用。

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

    另外,我假设您在问题中包含的代码是伪代码,如果不是,您可能会遗漏一些重要的东西(例如 navigation properties),也许以下内容会有所帮助:

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

    【讨论】:

    • 是的,它是一个伪代码,但我使用 dbcontext 上的模型构建器分配了密钥。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 2011-07-03
    • 2015-10-20
    • 2016-09-18
    • 2023-03-14
    相关资源
    最近更新 更多