【问题标题】:how to (INSERT) data in this table in entity framework code first?如何首先在实体框架代码中(插入)此表中的数据?
【发布时间】:2014-05-30 01:27:32
【问题描述】:

------
使用 EF 6
-------------------

我有 3 张桌子:

1) 用户

public class Users 
{
    [Key,Required, MaxLength(50)]
    public string UserName { get; set; }

    [Required, MaxLength(128)]
    public string Email { get; set; }

    [Required, MaxLength(128)]
    public string Password { get; set; }

}

2) 角色

public class Roles 
{
    [Key,Required, MaxLength(50)]
    public string RoleName { get; set; }

    [MaxLength(50)]
    public string ApplicationName { get; set; }
}

3) UsersInRoles //我的问题。

public class UsersInRoles 
{
    [Key]
    public int id { get; set; }

    [ForeignKey("Users"), Required]
    public string FKUserName { get; set; }
    public virtual Users Users { get; set; }

    [ForeignKey("Roles"), Required]
    public string FKRoleName { get; set; }
    public virtual Roles Roles { get; set; }
}

现在我的问题是如何在 UsersInRoles 表中插入记录???

我使用以下代码,但不在表中插入任何数据!
甚至不显示任何错误!

    List<UsersInRoles> BUsersInRoles = new List<UsersInRoles>
    {
        new UsersInRoles { FKUserName="User1", FKRoleName="Role1"},
        new UsersInRoles { FKUserName="User2", FKRoleName="Role2"}
    };

    foreach (UsersInRoles BIR in BUsersInRoles)
    {
        db.UsersInRoles.Add(BIR);
    }

    db.SaveChanges();

谢谢。

更新我发现了一个错误:

INSERT 语句与 FOREIGN KEY 约束冲突 “FK_dbo.UsersInRoles_dbo.Roles_FKRoleName”。冲突发生在 数据库“AriyaRad”、表“dbo.Roles”、“角色名称”列。这 语句已终止。

【问题讨论】:

  • Role1 和 Role2 是否存在于 Roles 表中?
  • 感谢 Evonet。在这个场景之前,我在角色表中插入角色和角色。

标签: entity-framework entity-framework-6


【解决方案1】:

我解决了我的问题!
原因是我为外键定义了单个字符串值,但尝试插入字符串值列表!

db.UsersInRoles.Add(new UsersInRoles {FKUserName="User1",
                FKRoleName="Role1", ApplicationName="PSCMS"});  
db.SaveChanges();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多