Tech-Today
Many to many relationship in Entity Framework
An example of many-to-many relationship is asp's membership tables, between aspnet_Users and aspnet_Roles. Usually we declare it like this:
public class AspUser {
public Guid UserId { get; set; }
...
public ICollection AspRoles { get; set; }
}
public class AspRole {
public Guid RoleId { get; set; }
...
public ICollection AspUsers { get; set; }
}
This will create a new table AspUsersAspRoles with UserId, and RoleId as columns. If you want to define your own table name (example AspUsersInRoles) you just need to override OnModelCreating:
modelBuilder.Entity()
.HasMany(r => r.AspRoles)
.WithMany(u => u.AspUsers)
.Map(m =>
{
m.ToTable("AspUsersInRoles");
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
});
-
Specify On Delete No Action Or On Update No Action, Or Modify Other Foreign Key Constraints
Have you encountered this error: "Introducing FOREIGN KEY constraint 'x_y_Target' on table 'z_UsersInRoles' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints."...
-
Executing A Linq Query With A Bridge Table Like Aspnet_users And Aspnet_roles
Using model first approach, we add aspnet_Users, aspnet_Roles and aspnet_UsersInRoles in the edmx file. But why is aspnet_UsersInRoles missing? It's because aspnet_Users has one-to-many relationship to aspnet_Roles. To get the role of the user, we...
-
Calling Mssql's Aspnet_membership_createuser Stored Procedure
Here's how you would want to call mssql's aspnet_Membership_CreateUser method: DECLARE @return_value int, @UserId uniqueidentifier, @nowUtc datetime, @now datetime set @nowUtc = getutcdate() set @now = getdate() EXEC @return_value = [dbo].[aspnet_Membership_CreateUser]...
-
How To Use Entityframework Codefirst To Update Your Database
This tutorial will attempt to explain how to update an already existing database using EntityFramework's CodeFirst approach. We need: 1.) VS2010 SP1 2.) NuGet 3.) EntityFramework 4.1 4.) EntityFramework.Migrations Steps: 1.) We need to make...
-
Create A Primary Key Column With Sequence Generated Value In Hibernate
For example you have a class User: package org.kalidad.seamexercises.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.SequenceGenerator;
...
Tech-Today