Created
May 26, 2017 00:08
-
-
Save luiseduardobraschi/3a36a8c6547ee06c1e0bb0b037acf3f8 to your computer and use it in GitHub Desktop.
Friendship workflow using Entity Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Data.Entity; | |
using System.Data.Entity.ModelConfiguration.Conventions; | |
namespace Test.Models { | |
public DbSet<Friendship> Friendships { get; set; } | |
protected override void OnModelCreating(DbModelBuilder modelBuilder) { | |
/* USER */ | |
modelBuilder.Entity<User>().HasMany(u => u.Friends).WithMany(); | |
/* FRIENDSHIP */ | |
modelBuilder.Entity<Friendship>().HasKey(f => new { f.SenderId, f.FriendId }); | |
modelBuilder.Entity<Friendship>() | |
.HasRequired(f => f.Sender) | |
.WithMany() | |
.HasForeignKey(f => f.SenderId); | |
modelBuilder.Entity<Friendship>() | |
.HasRequired(f => f.Friend) | |
.WithMany() | |
.HasForeignKey(f => f.FriendId) | |
.WillCascadeOnDelete(false); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.ComponentModel.DataAnnotations; | |
using System.ComponentModel.DataAnnotations.Schema; | |
namespace Test.Models { | |
public class Friendship { | |
public int SenderId { get; set; } | |
public virtual User Sender { get; set; } | |
public int FriendId { get; set; } | |
public virtual User Friend { get; set; } | |
public bool Accepted { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel.DataAnnotations; | |
using System.Collections.Generic; | |
using System.ComponentModel.DataAnnotations.Schema; | |
namespace Test.Models { | |
public class User { | |
public virtual ICollection<User> Friends { get; set; } | |
public User() { | |
this.Friends = new List<User>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment