I have a User Model
public class User {
public Guid IdGuid {get;set;}
public string Name {get;set;}
public virtual List<User> Friends {get;set;}
}
And I have second model
public class UserFriendship{
public Guid FriendShipIdGuid {get;set;}
public Guid UserIdGuid {get;set;}
public Guid FriendIdGuid {get;set;}
}
I have FluentApi code OnModelcreating
in context.
modelBuilder.Entity<User>().HasMany(u => u.Friends).WithMany().Map(c => {
c.MapLeftKey("UserIdGuid");
c.MapRightKey("FriendIdGuid");
c.ToTable("UserFriendship");
});
Problem : I already have a UserFriendship
class model. And I want to create relation about users to this model. And I am doing it with FluentApi.
But after FluentApi code executed, FriendShipIdGuid
is removed from UserFriendship
Table.
I need to create one to many relation for Users, and save it to table UserFriendship
and map it already existing class model name with UserFriendship
which element of dbset.
Can you help me please ?
As a summary, I already have UserFriendship
class. And this class contains FrientshipGuidId
(Key), UserIdGuid
, FriendIdGuid
.
I need to map, User
class one to many to itself.
And I want to save this relation on UserFriendship
class.
And I want to use Userfriendship
as dbset also.
I have
public DbSet<UserFriendship> Friendships { get;set; }
in my context.
I am using FluentApi ToTable
function to create one to many relation table.
But FluentApi code delete FriendshipIdGuid
field.
It's not possible. You can't use a List<UserFriendship>
in User
class either because sometimes a User is a user and other times a User is a friend, unless you have duplicates in your UserFriendship
table like this:
Friendship table: |
----------------------------
User / Friend
-------------
A / B
B / A
-------------
First change User
and UserFriendship
classes as follows:
class UserFriendship
{
public Guid FriendShipIdGuid {get;set;}
public Guid UserIdGuid {get;set;}
public Guid FriendIdGuid {get;set;}
public User User {get;set;}
public User Friend {get;set;}
}
class User
{
public Guid IdGuid {get;set;}
public string Name {get;set;}
// Only if you will allow duplicates in UserFriendship
public virtual List<UserFriendship> Friendships {get;set;}
}
I don't remember the exact syntax/methods of Fluent API but you will get the idea:
modelBuilder.Entity<User>()
.HasKey(u => u.IdGuid)
.ToTable("User");
modelBuilder.Entity<UserFriendship>()
.HasKey(uf => uf.FriendShipIdGuid)
.ToTable("UserFriendship");
modelBuilder.Entity<UserFriendship>()
.HasRequired(uf => uf.User)
.WithMany(u => u.Friendships) // Only if you allow duplicates
//.WithMany() // Otherwise
.HasForeignKey(uf => uf.UserIdGuid);
modelBuilder.Entity<UserFriendShip>()
.HasRequired(uf => uf.Friend)
.WithMany()
.HasForeignKey(uf => uf.FriendIdGuid);