how to (INSERT) data in this table in entity framework code first?

entity-framework entity-framework-6

Question

-------------------
using EF 6
-------------------

I have 3 table :

1) Users

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) Roles

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

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

3) UsersInRoles //My Problem.

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

Now my question is how to insert record in UsersInRoles table ???

i use following code but don't insert any data in table!
even don't show any errors!

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

Thanks.

Update: i have found a error :

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.UsersInRoles_dbo.Roles_FKRoleName". The conflict occurred in database "AriyaRad", table "dbo.Roles", column 'RoleName'. The statement has been terminated.

1
0
5/27/2014 9:28:20 PM

Popular Answer

I solve my problem!
The reason was i define single string value for Foreign Key but try to insert list of string value!

db.UsersInRoles.Add(new UsersInRoles {FKUserName="User1",
                FKRoleName="Role1", ApplicationName="PSCMS"});  
db.SaveChanges();
0
5/29/2014 5:27:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow