c# - Entityframework Core, code first, add a new table and it's relationships.

1. Define a new class, include existing class: AppUser.

    public class UserFollowing
    {
        public string ObserverId { get; set; }
        public virtual AppUser Observer { get; set; }
        public string TargetId { get; set; }
        public virtual AppUser Target { get; set; }
    }

2. In existing class: AppUser, add 2 new lists of the new class's instances:

    public class AppUser : IdentityUser
    {
        public string DisplayName { get; set; }

        public string Bio { get; set; }

        public virtual ICollection<UserActivity> UserActivities { get; set; }

        public virtual ICollection<Photo> Photos { get; set; }

        public virtual ICollection<UserFollowing> Followings { get; set; }
        
        public virtual ICollection<UserFollowing> Followers { get; set; }
    }

3. In DbContext's method: protected override void OnModelCreating(ModelBuilder builder), add relationships.

            builder.Entity<UserFollowing>(b =>
            {
                b.HasKey(k => new { k.ObserverId, k.TargetId });

                b.HasOne(o => o.Observer)
                 .WithMany(f => f.Followings)
                 .HasForeignKey(o => o.ObserverId)
                 .OnDelete(DeleteBehavior.Restrict);
                
                b.HasOne(o => o.Target)
                 .WithMany(f => f.Followers)
                 .HasForeignKey(o => o.ObserverId)
                 .OnDelete(DeleteBehavior.Restrict);
            });

4. Execute command: 

dotnet ef migrations add "AddedFlowingEntity" -p Persistence -s API

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章