I have two tables called Seminari and Predbiljezbe.
When I create a new data row in table Predbiljezbe, I want the row to take the primary key of table Seminari and insert it into table Predbiljezbe.
I'm hoping I made it clear, be mindful that since I am new to programming and would like help very much thank. I apologize for my bad English.
Here is my code:
Controller:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Predbiljezbe predbiljezbePrijava)
{
if (ModelState.IsValid)
{
context.Predbiljezbes.Add(predbiljezbePrijava);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(predbiljezbePrijava);
}
Entity model:
public partial class SeminariEntities1 : DbContext
{
public SeminariEntities1()
: base("name=SeminariEntities1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Predbiljezbe> Predbiljezbes { get; set; }
public virtual DbSet<Seminari> Seminaris { get; set; }
}
Predbiljezbe model:
public partial class Predbiljezbe
{
public int IdPredbiljezba { get; set; }
public string Ime { get; set; }
public string Prezime { get; set; }
public string Datum { get; set; }
public string Adresa { get; set; }
public string Email { get; set; }
public string Telefon { get; set; }
public bool Status { get; set; }
public Nullable<int> IdSeminara { get; set; }
public Nullable<int> BrojPolaznika { get; set; }
public virtual Seminari Seminari { get; set; }
}
Seminari model:
public partial class Seminari
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Seminari()
{
this.Predbiljezbes = new HashSet<Predbiljezbe>();
}
public int IdSeminar { get; set; }
public string Naziv { get; set; }
public string Opis { get; set; }
public System.DateTime Datum { get; set; }
public Nullable<bool> Popunjen { get; set; }
public string Predavač { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Predbiljezbe> Predbiljezbes { get; set; }
}
The way I do it is using double methods:
To insert into database and return Id
To insert dependent child using above Id
[HttpPost]
public ActionResult Create(Predbiljezbe predbiljezbePrijava)
{
if (ModelState.IsValid)
{
//add your first obj
context.Predbiljezbes.Add(predbiljezbePrijava);
context.SaveChanges();
//after saving in db its Id is automatically reflected in the object that you inserted
if(predbiljezbePrijava.Id != 0){
var seminariobj = new Seminari{ //insert your data }
// defining parentId into child
seminariobj.predbiljezbePrijavaId = predbiljezbePrijava.Id;
//save child obj
context.Seminari.Add(seminariobj);
context.SaveChanges();
}
return RedirectToAction("Index");
}
return View(predbiljezbePrijava);
}
I've tried your suggestion but i could not apply the solution to my problem,
Maybe there was an error in how I've set my tables and relations between them.
Here is my SQL query how i've set the tables in the database:
Seminari:
CREATE TABLE [dbo].[Seminari] (
[IdSeminar] INT IDENTITY (1, 1) NOT NULL,
[Naziv] NVARCHAR (MAX) NOT NULL,
[Opis] NVARCHAR (MAX) NULL,
[Datum] DATE NOT NULL,
[Popunjen] BIT NOT NULL,
[Predavač] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([IdSeminar] ASC)
);
Predbilježbe:
CREATE TABLE [dbo].[Predbiljezbe] (
[IdPredbiljezba] INT IDENTITY (1, 1) NOT NULL,
[Ime] NVARCHAR (MAX) NOT NULL,
[Prezime] NVARCHAR (MAX) NOT NULL,
[Datum] NVARCHAR (MAX) NOT NULL,
[Adresa] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NULL,
[Telefon] VARCHAR (MAX) NULL,
[Status] NVARCHAR (50) NULL,
[BrojPolaznika] INT NULL,
[IdSeminara] INT NULL,
CONSTRAINT [PK_Predbiljezbe] PRIMARY KEY CLUSTERED ([IdPredbiljezba] ASC),
CONSTRAINT [FK_Predbiljezbe_ToTable] FOREIGN KEY ([IdSeminara]) REFERENCES [dbo].[Seminari] ([IdSeminar])
);
Once again what i want is when i create new row in "Predbiljezbe" that column [IdSeminara] takes value of primary key [IdSeminar] from table "Seminari"!
Related
I am getting the following error when attempting to create a one-to-many relationship that has a multi value foreign key...
**
SQLite.Net.SQLiteException : foreign key mismatch - "Activity" referencing "Node"
**
This is the table SQL (simplified for clarity)...
CREATE TABLE [Activity] (
[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[InstId_FK] numeric(18,0) NOT NULL,
[NodeSeq_FK] numeric(3,0) NOT NULL,
[ActivityType] int NOT NULL,
CONSTRAINT [Node_FK] FOREIGN KEY([InstId_FK], [NodeSeq_FK]) REFERENCES [Node]([ID], [NodeSeq])ON DELETE CASCADE);
CREATE TABLE [Node] (
[ID] NUMERIC(18) NOT NULL CONSTRAINT [ID] REFERENCES [Trip]([ID]) ON DELETE CASCADE,
[NodeSeq] numeric(3,0) NOT NULL,
[Status] int,
[Name] nvarchar(30) NOT NULL,
CONSTRAINT [sqlite_autoindex_TripNode_1] PRIMARY KEY ([ID], [NodeSeq]));
And my C# Models (again simplified for clarity)...
public class TripNodeActivity : LocationAware
{
[PrimaryKey, AutoIncrement, ForeignKey(typeof(Node),Order = 1)]
public int Id { get; set; }
[Column("InstId_FK")]
public int InstIdFk { get; set; }
[Column("NodeSeq_FK"), ForeignKey(typeof(Node),Order = 2)]
public int NodeSeqFk { get; set; }
public int ActivityType { get; set; }
}
public class Node
{
public Node(){Activity = new List<Activity>();}
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<Activity> Activity{get;set;}
[PrimaryKey, ForeignKey(typeof(Trip))]
public int Id { get; set; }
[PrimaryKey]
public int NodeSeq { get; set; }
public int Status { get; set; }
public String Name { get; set; }
}
This error happens when trying to save the model using:
SQLiteConnection.InsertOrReplaceWithChildren(NodeFromAbove,true)
Few things there.
First, you have two PrimaryKey attributes in Node class. That is not supported in SQLite-Net.
Second, you are specifying that the PrimaryKey is also a ForeignKey for another table in both classes. That's not what you want to do.
Probably this is more likely what you were trying:
public class TripNodeActivity : LocationAware
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Column("InstId_FK")]
public int InstIdFk { get; set; }
[Column("NodeSeq_FK"), ForeignKey(typeof(Node)]
public int NodeSeqFk { get; set; }
public int ActivityType { get; set; }
}
public class Node
{
public Node(){Activity = new List<Activity>();}
[OneToMany(CascadeOperations = CascadeOperation.All)]
public List<Activity> Activity{get;set;}
[PrimaryKey]
public int Id { get; set; }
public int NodeSeq { get; set; }
public int Status { get; set; }
public String Name { get; set; }
}
Hope it helps.
I am new to MVC and I've got this annoying problem.
I am doing a small project to understand MVC better.
I am working in a code-first way.
I've created these two classes:
public class Post
{
[Required]
public int ID { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Text { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime Date { get; set; }
[Required]
public PostCategoryType Category { get; set; }
[Required]
public string PictureUrl { get; set; }
[Required]
public string VideoUrl { get; set; }
public virtual List<UserComment> Comments { get; set; }
}
public class UserComment
{
[Required]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string WebSite { get; set; }
[Required]
public string Comment { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime Date { get; set; }
}
public class MyStoreDbContext : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<UserComment> UsersComments { get; set; }
}
in order for the classes to be generated into tables at the entity framework I simply added controllers - one for each class and than ran the program and it generated the two tables.
The generated tables at the entity framework looks like this:
CREATE TABLE [dbo].[Posts] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (MAX) NOT NULL,
[Title] NVARCHAR (MAX) NOT NULL,
[Text] NVARCHAR (MAX) NOT NULL,
[Date] DATETIME NOT NULL,
[Category] INT NOT NULL,
[PictureUrl] NVARCHAR (MAX) NOT NULL,
[VideoUrl] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_dbo.Posts] PRIMARY KEY CLUSTERED ([ID] ASC)
);
CREATE TABLE [dbo].[UserComments] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (MAX) NOT NULL,
[Email] NVARCHAR (MAX) NOT NULL,
[WebSite] NVARCHAR (MAX) NOT NULL,
[Comment] NVARCHAR (MAX) NOT NULL,
[Date] DATETIME NOT NULL,
[Post_ID] INT NULL,
CONSTRAINT [PK_dbo.UserComments] PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_dbo.UserComments_dbo.Posts_Post_ID] FOREIGN KEY ([Post_ID]) REFERENCES [dbo].[Posts] ([ID])
);
GO
CREATE NONCLUSTERED INDEX [IX_Post_ID]
ON [dbo].[UserComments]([Post_ID] ASC);
I have a controller which have a data member of :
private MyStoreDbContext db = new MyStoreDbContext ();
in which I want my posts and user comments from.
Now to the problem:
When I access :
foreach(Post post in db.Posts)
{
post.Comments <------ This is always null
}
I've tried inserting a record of post with id 1 for example.
Than I inserted to the UserComments in which the post_id is the 1. (Both manually with VS Server Explorer);
when I try the code above the comments are always null.
I even tried different approach in which I manually inserted at debug time this:
UserComment comment = new UserComment... // Initialization
Post post = new Post.. // Initializing all but Comments
post.Comments = new List<UserComment>();
post.Comments.Add(comment);
db.Comments.Add(comment);
db.Posts.Add(post);
db.SaveChanges();
After all that, each and every post's comments property is null.
What am I missing?
Please help me as it is driving me crazy and accroding to other people's solutions to this problem online is exactly like this I cannot point out the problem.
Thanks in advance to all the helpers!
You need to add ID of Post in the UserComment class, like below:
public class UserComment
{
[Required]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string WebSite { get; set; }
[Required]
public string Comment { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime Date { get; set; }
public int PostID { get; set; }
[ForeignKey("PostID")]
public virtual Post Post { get; set; }
}
Then, Create a instance of Post first, like below:
var newPost = new Post{
UserName = "John",
//
}
db.Posts.Add(newPost );
db.SaveChanges();
After that, create a instance of UserComment, assign the ID of newPost to it, see below:
var comment = new UserComment
{
Name = "Some one",
//
PostID = newPost.ID
}
newPost.Comments.Add(comment);
db.SaveChanges();
Note:
You can learn more about this at below link:
http://codeblog.shawson.co.uk/entity-framework-4-1-code-first-with-one-to-many-relationship-code-example/
First of all I'd like to say, that I am super new to the MVC pattern, sorry if I am asking a stupid question.
My problem:
I am having trouble with the building of a profile page for my users. If a user goes to that page it's going to list information about them, like e-mail address, phone number, full name, etc..
Note:
I am using the "Basic" project template with SimpleMemberShipProvider hadling user actions.
The problem comes with the database querying, to get the necessary data about the user.
Here's my UserProfile table data:
CREATE TABLE [dbo].[UserProfile] (
[UserId] INT IDENTITY (1, 1) NOT NULL,
[UserName] NVARCHAR (MAX) NULL,
[FirstName] NVARCHAR (MAX) NULL,
[LastName] NVARCHAR (MAX) NULL,
[Age] INT NULL,
[Sex] NVARCHAR (MAX) NULL,
[SecretQuestion] NVARCHAR (MAX) NULL,
[SecretQuestionAnswer] NVARCHAR (MAX) NULL,
[MoneyIn] INT NULL,
[MoneyOut] INT NULL,
[TimesWon] INT NULL,
[Email] NVARCHAR (MAX) DEFAULT ('') NOT NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[Address] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.UserProfile] PRIMARY KEY CLUSTERED ([UserId] ASC)
);
My 'User' model:
[Table("UserProfile")]
public class User
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Column("UserName")]
public string UserName { get; set; }
[Column("Email")]
[Required]
public string Email { get; set; }
[Column("FirstName")]
public string FirstName { get; set; }
[Column("LastName")]
public string LastName { get; set; }
[Column("PhoneNumber")]
public string PhoneNumber { get; set; }
[Column("Address")]
public string Address { get; set; }
[Column("Age")]
[Required]
public int Age { get; set; }
[Column("Sex")]
public string Sex { get; set; }
[Column("SecretQuestion")]
[Required]
public string SecretQuestion { get; set; }
[Column("SecretQuestionAnswer")]
[Required]
public string SecretQuestionAnswer { get; set; }
[Column("MoneyIn")]
public int MoneyIn { get; set; }
[Column("MoneyOut")]
public int MoneyOut { get; set; }
[Column("TimesWon")]
public int TimesWon { get; set; }
}
Here's my DbContext class:
public DbSet<User> Users { get; set; }
My controller with the 'Profile' action:
[Authorize]
public ActionResult Profil()
{
var model = db.Users.ToList();
return View(model);
}
And finally some relevant parts of my view to display the data:
#model IEnumerable<OneMillion.Models.User>
#foreach (var item in Model)
{
#item.FirstName
}
The error I get when trying to access the page as a logged in user:
Server Error in '/' Application.
The 'MoneyIn' property on 'User' could not be set to a 'null' value. You must set this property to a non-null value of type 'Int32'.
Thanks!
try to set the properties to be a nullable type ->
[Column("MoneyIn")]
public int? MoneyIn { get; set; }
[Column("MoneyOut")]
public int? MoneyOut { get; set; }
Your model and database definitions don't match, you have nullable fields in the database definition (Age, MoneyIn, MoneyOut and TimesWon) but non-nullable fields in the model.
Have a code first MVC4 model that requires foreign key look up to the same table. i.e My Project table has two columns (BaseFiscalId and IMITApprovalCycleId) that reference the same table i.e. FiscalYears. How do I define this in the code.
Currently I have the following:
public class Project
{
[Required]
public int Id { get; set; }
[Required]
public int InitiativeId { get; set; }
[Required]
public String ProjectName { get; set; }
[Required]
public int SubPortFolioId { get; set; }
[Required]
public String Description { get; set; }
[Required]
public int ProjectTypeId { get; set; }
[Required]
public int FundingSourceId { get; set; }
[Required]
public int FundingPhaseAId { get; set; }
[Required]
public int ApprovalStatusId { get; set; }
[Required]
public int IMITApprovalProcessId { get; set; }
[Required]
public int IMITApprovalCycleId { get; set; }
[Required]
public int AccountableExecutiveId { get; set; }
[Required]
public int LeadMinistryId { get; set; }
[Required]
public int BaseFiscalId { get; set; }
[Required]
public int TotalSpentToBase { get; set; }
//Navigation Properties --Child Projects
public ICollection<Spend> Spends { get; set; }
public SubPortfolio SubPortfolio { get; set; }
public ProjectType ProjectType { get; set; }
public FundingPhase FundingPhase { get; set; }
public FundingSource FundingSource { get; set; }
public ApprovalStatus ApprovalStatus { get; set; }
public IMITApprovalProcess IMITApprovalProcess { get; set; }
public FiscalYear IMITApprovalCycle { get; set; }
public FiscalYear BaseFiscal { get; set; }
public Portfolio Portfolio { get; set; }
public Executive AccountableExecutive { get; set; }
public Ministry LeadMinistry { get; set; }
public Initiative Initiative { get; set; }
}
FiscalYears Class
public class FiscalYear
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required]
public String FiscalYearName { get; set; }
}
This results in the following SQL:
CREATE TABLE [dbo].[Projects] (
[Id] INT NOT NULL,
[InitiativeId] INT NOT NULL,
[ProjectName] NVARCHAR (MAX) NOT NULL,
[SubPortFolioId] INT NOT NULL,
[Description] NVARCHAR (MAX) NOT NULL,
[ProjectTypeId] INT NOT NULL,
[FundingSourceId] INT NOT NULL,
[FundingPhaseAId] INT NOT NULL,
[ApprovalStatusId] INT NOT NULL,
[IMITApprovalProcessId] INT NOT NULL,
[IMITApprovalCycleId] INT NOT NULL,
[AccountableExecutiveId] INT NOT NULL,
[LeadMinistryId] INT NOT NULL,
[BaseFiscalId] INT NOT NULL,
[TotalSpentToBase] INT NOT NULL,
[FundingPhase_Id] INT NULL,
[Portfolio_Id] INT NULL,
[Initiative_Id] INT NULL,
CONSTRAINT [PK_dbo.Projects] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.Projects_dbo.SubPortfolios_SubPortFolioId] FOREIGN KEY ([SubPortFolioId]) REFERENCES [dbo].[SubPortfolios] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Projects_dbo.ProjectTypes_ProjectTypeId] FOREIGN KEY ([ProjectTypeId]) REFERENCES [dbo].[ProjectTypes] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Projects_dbo.FundingPhases_FundingPhase_Id] FOREIGN KEY ([FundingPhase_Id]) REFERENCES [dbo].[FundingPhases] ([Id]),
CONSTRAINT [FK_dbo.Projects_dbo.FundingSources_FundingSourceId] FOREIGN KEY ([FundingSourceId]) REFERENCES [dbo].[FundingSources] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Projects_dbo.ApprovalStatus_ApprovalStatusId] FOREIGN KEY ([ApprovalStatusId]) REFERENCES [dbo].[ApprovalStatus] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Projects_dbo.IMITApprovalProcesses_IMITApprovalProcessId] FOREIGN KEY ([IMITApprovalProcessId]) REFERENCES [dbo].[IMITApprovalProcesses] ([Id]) ON DELETE CASCADE,
**CONSTRAINT [FK_dbo.Projects_dbo.FiscalYears_Id] FOREIGN KEY ([Id]) REFERENCES [dbo].[FiscalYears] ([Id])**,
CONSTRAINT [FK_dbo.Projects_dbo.Portfolios_Portfolio_Id] FOREIGN KEY ([Portfolio_Id]) REFERENCES [dbo].[Portfolios] ([Id]),
CONSTRAINT [FK_dbo.Projects_dbo.Executives_AccountableExecutiveId] FOREIGN KEY ([AccountableExecutiveId]) REFERENCES [dbo].[Executives] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Projects_dbo.Ministries_LeadMinistryId] FOREIGN KEY ([LeadMinistryId]) REFERENCES [dbo].[Ministries] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.Projects_dbo.Initiatives_Initiative_Id] FOREIGN KEY ([Initiative_Id]) REFERENCES [dbo].[Initiatives] ([Id])
Note instead of creating two FK relationships to FiscalYears One each for BaseFiscal and IMITApprovalCycle it create only on on Fiscal_Id which does not exist in the Projects Table.
Thanks
Craig
I have a MS-SQL table as shown below.
Users Table
CREATE TABLE [dbo].[Users](
[UserId] [uniqueidentifier] NOT NULL Primary Key,
[UserAccount] [nvarchar](50) NOT NULL Unique,
[Password] [nvarchar](50) NOT NULL,
[UserEmail] [nvarchar](50) NOT NULL,
[JoinDate] [datetime2](7) NOT NULL,
[LoginDate] [datetime2](7) NULL)
Roles Table
CREATE TABLE [dbo].[Roles](
[RoleId] [uniqueidentifier] NOT NULL Primary Key,
[RoleName] [nvarchar](50) NOT NULL Unique,
[Note] [nvarchar](50) NOT NULL,
[RegistDate] [datetime2](7) NOT NULL)
UsersInRoles Table
CREATE TABLE [dbo].[UsersInRoles](
[UserId] [uniqueidentifier] NOT NULL,
[RoleId] [uniqueidentifier] NOT NULL,
[SetDate] [datetime2](7) NOT NULL,
PRIMARY KEY CLUSTERED (
[UserId] ASC,
[RoleId] ASC)WITH (
PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
GO
ALTER TABLE [dbo].[UsersInRoles] WITH CHECK ADD FOREIGN KEY([RoleId]) REFERENCES [dbo].[Roles] ([RoleId]) GO
ALTER TABLE [dbo].[UsersInRoles] WITH CHECK ADD FOREIGN KEY([UserId]) REFERENCES [dbo].[Users] ([UserId]) GO
I'm trying to express in EF Code-First of this.
User Entity Class
public class User
{
public Guid UserId { get; set; }
public string UserAccount { get; set; }
public string Password { get; set; }
public string UserEmail { get; set; }
public DateTime JoinDate { get; set; }
public DateTime LoginDate { get; set; }
}
Role Entity Class
public class Role
{
public Guid RoleId { get; set; }
public string RoleName { get; set; }
public string Note { get; set; }
public DateTime RegistDate { get; set; }
}
UsersInRole Entity Class
public class UsersInRole
{
public Guid UserId { get; set; }
public Guid RoleId { get; set; }
public DateTime SetDate { get; set; }
}
The problem of the foreign key, How should designed UsersInRoles?
Please let me know if there is a better design.
It's not really code first if you are designing your database and then making the code conform, is it? Sounds like you should have a roles collection defined on your User class and then let EntityFramework do the work of building that intermediate table. It will handle the FK relationships.
I haven't tried running the following code, so I aren't 100% sure.
However I would start out with something like ...
in your domain classes
public class User
{
public Guid UserId { get; set; }
public string UserAccount { get; set; }
public string Password { get; set; }
public string UserEmail { get; set; }
public DateTime JoinDate { get; set; }
public DateTime LoginDate { get; set; }
}
public class Role
{
public Guid RoleId { get; set; }
public string RoleName { get; set; }
public string Note { get; set; }
public DateTime RegistDate { get; set; }
}
public class UsersInRole
{
public DateTime SetDate { get; set; }
virtual User User { get; set; }
virtual Role Role { get; set; }
}
in your context you need
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UsersInRole> UsersInRoles { get; set; }
optionally you might want to include
public virtual ICollection<UsersInRole> Roles { get; private set; }
in the User class
and/or
public virtual ICollection<UsersInRole> Users { get; private set; }
in the role class
Which will keep the same data structure.