Skip to content

Instantly share code, notes, and snippets.

@luiseduardobraschi
Created May 26, 2017 00:08
Show Gist options
  • Save luiseduardobraschi/3a36a8c6547ee06c1e0bb0b037acf3f8 to your computer and use it in GitHub Desktop.
Save luiseduardobraschi/3a36a8c6547ee06c1e0bb0b037acf3f8 to your computer and use it in GitHub Desktop.
Friendship workflow using Entity Framework
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);
}
}
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; }
}
}
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