ASP.NET Model Relationship - asp.net-web-api

I'm currently learning ASP.NET MVC and Web API.
I'm trying to create a User Model. Users can have any number of UserContacts. UserContacts reference the User it is a contact of and the User who is the contact. I have made a model called UserContact because attached to this Model is additional information.
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class UserContact
{
public int UserContactID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID"), Column(Order = 0)]
[Required]
public User User { get; set; }
public int ContactID { get; set; }
[ForeignKey("ContactID"), Column(Order = 1)]
[Required]
public User Contact { get; set; }
public DateTime ContactSince { get; set; }
}
So this gives me an error referring to cascading Delete. How do I set up a relationship like this where two foreign keys point to the same Model type? I have yet to grasp Entity Framework syntax as well. If I don't have an ICollection of UserContacts in the User model, does this hinder my ability to grab the UserContacts associated with that User?

When you have a foreign key and the foreign key columns are not nullable(means,required). EF will automatically tries to enable cascading delete on the relationsip. In your case, it will try to enable Cascading delete for both the foreign key columns and both of them points to the same user table! That is the reason you are getting this error. What if you have a UserContact record with Both UserId and ContactID points to the same User record. Cascading delete is confused now :)
Also, since one user can have more than one Contacts, We need a Contacts property on the User table to represent that. This will be a collection of UserContact's. Also this user can be a a contact of many other people. So Let's create another property for that.
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<UserContact> Contacts { set; get; }
public ICollection<UserContact> ContactOf { set; get; }
}
public class UserContact
{
public int UserContactID { get; set; }
public int UserID { get; set; }
public User User { get; set; }
public int ContactID { get; set; }
public User Contact { get; set; }
public DateTime ContactSince { get; set; }
}
And in your DbContext class, We can configure the foreign key relation ships and tell EF to disable cascade delete using fluent configuration inside the overridden OnModelCreating method. The below code will disable cascading delete on both the the relationships. But for your error to go away. disabling on one foreign key is enough.
public class YourDbContext: DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserContact>()
.HasRequired<User>(g=>g.User)
.WithMany(g=>g.Contacts)
.HasForeignKey(g=>g.UserID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<UserContact>()
.HasRequired<User>(g => g.Contact)
.WithMany(g => g.ContactOf)
.HasForeignKey(g => g.ContactID)
.WillCascadeOnDelete(false); // this one is not really needed to fix the error
base.OnModelCreating(modelBuilder);
}
public DbSet<User> Users { set; get; }
public DbSet<UserContact> UserContacts { set; get; }
}
This will create the tables like you wanted with the necessary foreign keys.

There is not enough information for EF to figure out the relationships on the other side, so yes, you need collections. You can use the InverseProperty annotation to clarify (or fluent api statements):
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[InverseProperty("User")]
public Virtual ICollection<UserContact> Users{ get; set; }
[InverseProperty("Contact")]
public Virtual ICollection<UserContact> Contacts { get; set; }
}
public class UserContact
{
public int UserContactID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID"), Column(Order = 0)]
[Required]
public User User { get; set; }
public int ContactID { get; set; }
[ForeignKey("ContactID"), Column(Order = 1)]
[Required]
public User Contact { get; set; }
public DateTime ContactSince { get; set; }
}
http://www.entityframeworktutorial.net/code-first/inverseproperty-dataannotations-attribute-in-code-first.aspx

Related

How to update an existing object in a many to many relationship (.Net 5)

I have been using the .Net 5 and EF Core 5 for a small web app. Given EF Core 5 supports many - many out of the box there is no need for a joining table.
I've run into an issue when updating a object that already exists in the DB. For my app I have Athletes and Parents which have the many - many relationship.
public class Athlete
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Email { get; set; }
public string ContactNumber { get; set; }
public string Street { get; set; }
public int Postcode { get; set; }
public string City { get; set; }
public StateEnum State { get; set; }
public DateTime DateofBirth { get; set; }
public DateTime DateSignedUp {get; set;}
public virtual ICollection<Parent> Parents { get; set; }
}
public class Parent
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Email { get; set; }
public string ContactNumber { get; set; }
public string Street { get; set; }
public int Postcode { get; set; }
public string City { get; set; }
public StateEnum State { get; set; }
public DateTime DateofBirth { get; set; }
public DateTime DateSignedUp {get; set;}
public virtual ICollection<Athlete> Athletes { get; set; }
}
When I try to update the existing athlete that has a relation ship with two other parents I get an error:
Violation of PRIMARY KEY constraint 'PK_AthleteParent'. Cannot insert
duplicate key in object 'dbo.AthleteParent'. The duplicate key value
is (31, 1)
[HttpPost]
public async Task<ActionResult<Athlete>> PostAthlete(Athlete athlete)
{
_context.Athletes.Update(athlete);
await _context.SaveChangesAsync();
return Ok(athlete));
}
From what I can tell when entity tries to update my Athlete it tries to insert new rows into the joining table even though the parents already exist in there. Is there a way to get entity to remove any records when the relationship is updated? Or is there a way to tell entity to take update the joining table to match the Athlete object that is passed in?
Given a simple example like this:
public class Foo {
Guid Id { get; set; }
ICollection<Bar> Bars { get; set; }
}
public class Bar {
Guid Id { get; set; }
ICollection<Foo> Foos { get; set; }
}
You can call clear() on a tracked instance of Foo, and then re-add the Bar instances that you want assigned. I've found this is a nice way to avoid the constraint exception - much easier than manually trying to figure out what Bars have changed.
var foo = context.Foos.Include(x => x.Bars).FirstOrDefault(x => x.Id == someGuid);
foo.Bars.Clear();
foo.Bars.Add(bar1);
foo.Bars.Add(bar2);
...
context.Update(foo);
context.SaveChanges();

How to use checklistbox to update roles in account in mvc3

I have any Model
public class Account
{
[Key]
public int AccountID { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FullName { get; set; }
}
And
public class Role
{
[Key]
public int RoleID { get; set; }
public string RoleKey { get; set; }
public string RoleName { get; set; }
}
And
public class AccountRole
{
[Key]
public int ID { get; set; }
public int AccountID { get; set; }
public string Role { get; set; }
}
I want to use one view update Account and list role to list checkbox. When I checked in checkbox then role to insert in to AccountRole.
Please tell me how to create my View.
Create a holder for a Role + a boolean IsSelected
public class SelectionRoles
{
public bool IsSelected { get; set;}
public Role OneRole { get; set; }
}
use this in your ViewModel as a List, pass it to your View and use it for display, when you submit your form you can check in your controller which roles are checked by looking in your ViewModel at the IsSelected boolean for each record in your SelectionRole List.

Entity Framework POCO Relationships

I am trying to implement code-first approach of entity framework. I have four entities UserInfo, Client, Admin and Account. I want relationships as:
Each Client has a UserInfo
Each Admin has a `UserInfo
Each Account is linked with a User(UserInfo)
Assuming these things i wrote the POCO models. With the relationships i want, is it correct ?Am i missing something?
public class UserInfo
{
public int UserInfoID { get; set; }
public Name Name { get; set; }
public Address Address { get; set; }
public Contact Contact { get; set; }
}
public class Admin
{
public int AdminID { get; set; }
public int UserInfoID { get; set; }
[ForeignKey("UserInfoID")]
public virtual UserInfo UserInfo { get; set; }
}
public class Client
{
public int ClientID { get; set; }
public CompanyDetails CompanyDetails { get; set; }
public int UserInfoID { get; set; }
[ForeignKey("UserInfoID")]
public virtual UserInfo UserInfo { get; set; }
}
public class Account
{
public int AccountID { get; set; }
[Required, Column("Balance"), Display(Name = "Account Balance")]
public double Balance { get; set; }
public int UserInfoID { get; set; }
[ForeignKey("UserInfoID")]
public virtual UserInfo UserInfo { get; set; }
}
What you have appears to be correct based on your requirements however I personally prefer the Entity Framework Model Builder when configuring your entities with Code First.
Using the model builder means that you don't have any attributes on your POCO entities which in turn means that you don't need an EF reference to use the entities.
Take a look at my article here for some more info on how to use the modelbuilder : http://blog.staticvoid.co.nz/2012/07/entity-framework-navigation-property.html

EF multiple relationships between entities

I'm using the Code First approach to build the database in this problem. I have the following (partial) entity:
public class Tournament {
public int TournamentID { get; set; }
public String Name { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public int? SportID { get; set; }
public virtual Sport Sport { get; set; }
public virtual ICollection<Official> Officials { get; set; }
}
In the Official Entity I have this:
public class Official {
public int OfficialID { get; set; }
public String Surname { get; set; }
public String FirstName { get; set; }
public int? TournamentID { get; set; }
public virtual Tournament Tournament { get; set; }
public virtual ICollection<Match> Matches { get; set; }
}
Using some sample data and checking the SQL Server database, this works as I would expect it to. The tournament has a one-to-many relationship with officials.
The problem I'm having is that I would like the tournament to hold the primary key of an official as the head official. So I would add to the Tournament entity:
public int? OfficialID { get; set; } // foreign key to official table
public virtual Official HeadOfficial { get; set; } // navigation property
If I do this I get an attribute OfficialID and HeadOfficial_OfficialID in my Tournament table and I get TournamentID, Tournament_TournamentID and Tournament_TournamentID1 in my Officials table. I realise I now not only have a one-to-many relationship between Tournament and Official (seeing as a tournament can have many officials), but I also have a one-to-one relationship (seeing as a tournament can only have one head official).
How can I fix this problem?
You can fix the problem by giving EF a hint which navigation properties belong together. EF conventions cannot decide this anymore when you have two navigation properties in a class which refer to the same target class:
public class Tournament {
public int TournamentID { get; set; }
//...
public int? OfficialID { get; set; }
[ForeignKey("OfficialID")]
public virtual Official HeadOfficial { get; set; }
[InverseProperty("Tournament")] // the navigation property in Official class
public virtual ICollection<Official> Officials { get; set; }
}
It's also possible with Fluent API if you prefer that:
modelBuilder.Entity<Tournament>()
.HasOptional(t => t.HeadOfficial)
.WithMany()
.HasForeignKey(t => t.OfficialID);
modelBuilder.Entity<Tournament>()
.HasMany(t => t.Officials)
.WithOptional(o => o.Tournament)
.HasForeignKey(o => o.TournamentID);

EF 4.1 Code First multiple Many-to-Many relationships

I'm having trouble wrapping my head around a certain code-first relationship. I have three entities: Group, User, GroupPermission. The GroupPermission entity holds information about permissions that relate to a group. There are three permissions: leader, editor, user. The GroupPermission table should include the primary key Id and the name of the permission. Then I want a relationship table that looks something like this: Id - Group_Id - User_Username - GroupPermission_Id. There can be multiple groups, multiple users, multiple permissions. I have plenty of examples that help me make a single relationship table, but I can't find anything that includes multiple relationships.
Here are my entities...
User:
public class User
{
[Key, StringLength(EntityLength.UsernameLength)]
public string Username { get; set; }
[Required, StringLength(EntityLength.NameLength)]
public string FirstName { get; set; }
[Required, StringLength(EntityLength.NameLength)]
public string LastName { get; set; }
[Required, StringLength(EntityLength.Email)]
public string Email { get; set; }
public bool Active { get; set; }
public DateTime DateCreated { get; set; }
public virtual UserPermission UserPermission { get; set; }
public virtual ICollection<Group> Groups { get; set; }
public virtual ICollection<Project> Projects { get; set; }
public virtual ICollection<Issue> Issues { get; set; }
public virtual ICollection<GroupPermission> GroupPermissions { get; set; }
public string FullName
{
get { return FirstName + ' ' + LastName; }
}
}
Group:
public class Group
{
[Key]
public int Id { get; set; }
[Required, StringLength(EntityLength.GenericLength)]
public string Name { get; set; }
[Required, StringLength(EntityLength.DescriptionLength)]
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Project> Projects { get; set; }
public virtual ICollection<GroupPermission> GroupPermissions { get; set; }
}
GroupPermission:
public class GroupPermission
{
[Key]
public int Id { get; set; }
[StringLength(EntityLength.GenericLength)]
public string Name { get; set; }
public int GroupId { get; set; }
public virtual ICollection<Group> Groups { get; set; }
public int UserId { get; set; }
public virtual ICollection<User> Users { get; set; }
public enum Permission
{
Leader = 1,
Editor = 2,
User = 3
}
}
When the tables are created using this structure, I get a GroupPermissions table that has Id, Name, GroupId, and UserId. This table needs to only be Id and Name. Then it creates a GroupPermissionUsers table that holds GroupPermissions_Id and User_Username. This is the table that should be Id, Group_Id, User_Username, GroupPermission_Id.
Does anybody have any tips to accomplish this or am I thinking about the design of this incorrectly?
In such case you are missing additional entity. It should look like:
New Permission entity with Id and Name:
public class Permission
{
[Key]
public int Id { get; set; }
[StringLength(EntityLength.GenericLength)]
public string Name { get; set; }
public virtual ICollection<GroupPermission> GroupPermissions { get; set; }
}
Modified GroupPermission entity to form junction table among Users, Groups and Permissions:
public class GroupPermission
{
[Key]
public int Id { get; set; }
public int GroupId { get; set; }
public virtual Group Group { get; set; }
public string UserName { get; set; }
[ForeignKey("UserName")]
public virtual User User { get; set; }
public int PermissionId { get; set; }
public virtual Permission Permission { get; set; }
}

Resources