EF Core one-to-many or many-to-many ? usersfriends











up vote
2
down vote

favorite












I'm going to implement a user-friends module in my project.



Let's say I have 2 simple classes:



public class User
{
int Id { get; set; }
string Name { get; set; }
}


and FriendShip class (which is a relation between user)



   public class FriendShip
{
int User1Id { get; set; }
int User2Id { get; set; }
int Status { get; set; }
}


Status is Enum



Logic for these 2 classes:





  • when first user invite second user to his friendship-list, there should be 2 objects created in the database



    user1Id: 1,
    user2Id: 2,
    Status: 1, (where 1 means 'invited')


    and



    user1Id: 2,
    user2Id: 1,
    Status: 0, (where 0 means 'nonaccepted')


  • when second user accepts, these 2 status will be updated by value 3 (where means 'friendship' or something like that - but forget about logic now.



I don't know how can i create this database structure from code (in C#)



it will be one-to-many, like one user can have many relationships to other-users?



thee private key must be 2 fk: user1, user2



the problem is, that these 2 foreign keys goes to one table (Users)



I tried something like this:



    modelBuilder.Entity<User>()
.HasMany(x=>x.UsersFriendships)
.WithOne(x=>x.User2)

modelBuilder.Entity<UsersFriendship>()
.HasMany(x=> x.Users)
.WithOne(x=>x.UsersFriendships)


but it does not have sense, I can't do the second statement



.WithOne(x => x.userFriendships)


The simplest way is to type in model builder:



 modelBuilder.Entity<UsersFriendship>()
.HasKey(x => new { x.User1Id, x.User2Id });


and the class UserFriendship will be like this:



   public class UsersFriendship
{

[ForeignKey("User1Id")]
public User User1 { get; set; }

[ForeignKey("User2Id")]
public User User2 { get; set; }

public int User1Id { get; set; }
public int User2Id { get; set; }
public RelationStatus RelationStatus { get; set; }
}


but from now, i cannot naviage from User entity to his friends (like User.Friendship)



and when i add navigation property to User class:



public virtual List<UsersFriendship> UsersFriendships { get; set; }


the database will four fields: user1Id, user2Id, status, userId



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!










share|improve this question
























  • by the way, I am assuming your friends are not ships (put "ship" in lowercase in class Friendship)
    – B12Toaster
    Nov 11 at 14:43

















up vote
2
down vote

favorite












I'm going to implement a user-friends module in my project.



Let's say I have 2 simple classes:



public class User
{
int Id { get; set; }
string Name { get; set; }
}


and FriendShip class (which is a relation between user)



   public class FriendShip
{
int User1Id { get; set; }
int User2Id { get; set; }
int Status { get; set; }
}


Status is Enum



Logic for these 2 classes:





  • when first user invite second user to his friendship-list, there should be 2 objects created in the database



    user1Id: 1,
    user2Id: 2,
    Status: 1, (where 1 means 'invited')


    and



    user1Id: 2,
    user2Id: 1,
    Status: 0, (where 0 means 'nonaccepted')


  • when second user accepts, these 2 status will be updated by value 3 (where means 'friendship' or something like that - but forget about logic now.



I don't know how can i create this database structure from code (in C#)



it will be one-to-many, like one user can have many relationships to other-users?



thee private key must be 2 fk: user1, user2



the problem is, that these 2 foreign keys goes to one table (Users)



I tried something like this:



    modelBuilder.Entity<User>()
.HasMany(x=>x.UsersFriendships)
.WithOne(x=>x.User2)

modelBuilder.Entity<UsersFriendship>()
.HasMany(x=> x.Users)
.WithOne(x=>x.UsersFriendships)


but it does not have sense, I can't do the second statement



.WithOne(x => x.userFriendships)


The simplest way is to type in model builder:



 modelBuilder.Entity<UsersFriendship>()
.HasKey(x => new { x.User1Id, x.User2Id });


and the class UserFriendship will be like this:



   public class UsersFriendship
{

[ForeignKey("User1Id")]
public User User1 { get; set; }

[ForeignKey("User2Id")]
public User User2 { get; set; }

public int User1Id { get; set; }
public int User2Id { get; set; }
public RelationStatus RelationStatus { get; set; }
}


but from now, i cannot naviage from User entity to his friends (like User.Friendship)



and when i add navigation property to User class:



public virtual List<UsersFriendship> UsersFriendships { get; set; }


the database will four fields: user1Id, user2Id, status, userId



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!










share|improve this question
























  • by the way, I am assuming your friends are not ships (put "ship" in lowercase in class Friendship)
    – B12Toaster
    Nov 11 at 14:43















up vote
2
down vote

favorite









up vote
2
down vote

favorite











I'm going to implement a user-friends module in my project.



Let's say I have 2 simple classes:



public class User
{
int Id { get; set; }
string Name { get; set; }
}


and FriendShip class (which is a relation between user)



   public class FriendShip
{
int User1Id { get; set; }
int User2Id { get; set; }
int Status { get; set; }
}


Status is Enum



Logic for these 2 classes:





  • when first user invite second user to his friendship-list, there should be 2 objects created in the database



    user1Id: 1,
    user2Id: 2,
    Status: 1, (where 1 means 'invited')


    and



    user1Id: 2,
    user2Id: 1,
    Status: 0, (where 0 means 'nonaccepted')


  • when second user accepts, these 2 status will be updated by value 3 (where means 'friendship' or something like that - but forget about logic now.



I don't know how can i create this database structure from code (in C#)



it will be one-to-many, like one user can have many relationships to other-users?



thee private key must be 2 fk: user1, user2



the problem is, that these 2 foreign keys goes to one table (Users)



I tried something like this:



    modelBuilder.Entity<User>()
.HasMany(x=>x.UsersFriendships)
.WithOne(x=>x.User2)

modelBuilder.Entity<UsersFriendship>()
.HasMany(x=> x.Users)
.WithOne(x=>x.UsersFriendships)


but it does not have sense, I can't do the second statement



.WithOne(x => x.userFriendships)


The simplest way is to type in model builder:



 modelBuilder.Entity<UsersFriendship>()
.HasKey(x => new { x.User1Id, x.User2Id });


and the class UserFriendship will be like this:



   public class UsersFriendship
{

[ForeignKey("User1Id")]
public User User1 { get; set; }

[ForeignKey("User2Id")]
public User User2 { get; set; }

public int User1Id { get; set; }
public int User2Id { get; set; }
public RelationStatus RelationStatus { get; set; }
}


but from now, i cannot naviage from User entity to his friends (like User.Friendship)



and when i add navigation property to User class:



public virtual List<UsersFriendship> UsersFriendships { get; set; }


the database will four fields: user1Id, user2Id, status, userId



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!










share|improve this question















I'm going to implement a user-friends module in my project.



Let's say I have 2 simple classes:



public class User
{
int Id { get; set; }
string Name { get; set; }
}


and FriendShip class (which is a relation between user)



   public class FriendShip
{
int User1Id { get; set; }
int User2Id { get; set; }
int Status { get; set; }
}


Status is Enum



Logic for these 2 classes:





  • when first user invite second user to his friendship-list, there should be 2 objects created in the database



    user1Id: 1,
    user2Id: 2,
    Status: 1, (where 1 means 'invited')


    and



    user1Id: 2,
    user2Id: 1,
    Status: 0, (where 0 means 'nonaccepted')


  • when second user accepts, these 2 status will be updated by value 3 (where means 'friendship' or something like that - but forget about logic now.



I don't know how can i create this database structure from code (in C#)



it will be one-to-many, like one user can have many relationships to other-users?



thee private key must be 2 fk: user1, user2



the problem is, that these 2 foreign keys goes to one table (Users)



I tried something like this:



    modelBuilder.Entity<User>()
.HasMany(x=>x.UsersFriendships)
.WithOne(x=>x.User2)

modelBuilder.Entity<UsersFriendship>()
.HasMany(x=> x.Users)
.WithOne(x=>x.UsersFriendships)


but it does not have sense, I can't do the second statement



.WithOne(x => x.userFriendships)


The simplest way is to type in model builder:



 modelBuilder.Entity<UsersFriendship>()
.HasKey(x => new { x.User1Id, x.User2Id });


and the class UserFriendship will be like this:



   public class UsersFriendship
{

[ForeignKey("User1Id")]
public User User1 { get; set; }

[ForeignKey("User2Id")]
public User User2 { get; set; }

public int User1Id { get; set; }
public int User2Id { get; set; }
public RelationStatus RelationStatus { get; set; }
}


but from now, i cannot naviage from User entity to his friends (like User.Friendship)



and when i add navigation property to User class:



public virtual List<UsersFriendship> UsersFriendships { get; set; }


the database will four fields: user1Id, user2Id, status, userId



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!







c# ef-core-2.0






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 16:06

























asked Nov 11 at 10:36









IchLiebeKadarka

205




205












  • by the way, I am assuming your friends are not ships (put "ship" in lowercase in class Friendship)
    – B12Toaster
    Nov 11 at 14:43




















  • by the way, I am assuming your friends are not ships (put "ship" in lowercase in class Friendship)
    – B12Toaster
    Nov 11 at 14:43


















by the way, I am assuming your friends are not ships (put "ship" in lowercase in class Friendship)
– B12Toaster
Nov 11 at 14:43






by the way, I am assuming your friends are not ships (put "ship" in lowercase in class Friendship)
– B12Toaster
Nov 11 at 14:43














1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










You can find one example in the official docs: https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many.



I adjusted this example to reflect your case:



namespace foo
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<UsersFriendship> UsersFriendships { get; set; }
}

public class Friendship
{
public User User1 { get; set; }
public int User1Id { get; set; }
public User User2 { get; set; }
public int User2Id { get; set; }
public int Status { get; set; }
}

class MyContext : DbContext
{
public DbSet<Friendship> Friendships { get; set; }
public DbSet<User> Users { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Friendship>()
.HasKey(fs => new { fs.User1, fs.User2, fs.Status });

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User1)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User1);

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User2)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User2);
}
}



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!




When registering this as navigational property (see my code) then it will not be stored in db.



In other cases, if for some reason you don't want a property to be stored in db by ef core, mark the property with the [NotMapped] attribute (namespace System.ComponentModel.DataAnnotations.Schema).






share|improve this answer























  • not really, please read topic one more time
    – IchLiebeKadarka
    Nov 11 at 15:46










  • are you sure? I updated my example to match your problem. please check again.
    – B12Toaster
    Nov 11 at 16:02










  • i'm sorry but in meantime i have updated my post. now your example do same thinks like mine with attributes i think. but i dont know what should i do to have navigation property in Userclass, but to don't have additional field in database
    – IchLiebeKadarka
    Nov 11 at 16:08










  • give me a second will update my example [done]
    – B12Toaster
    Nov 11 at 16:16













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53247895%2fef-core-one-to-many-or-many-to-many-users-friends%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote



accepted










You can find one example in the official docs: https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many.



I adjusted this example to reflect your case:



namespace foo
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<UsersFriendship> UsersFriendships { get; set; }
}

public class Friendship
{
public User User1 { get; set; }
public int User1Id { get; set; }
public User User2 { get; set; }
public int User2Id { get; set; }
public int Status { get; set; }
}

class MyContext : DbContext
{
public DbSet<Friendship> Friendships { get; set; }
public DbSet<User> Users { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Friendship>()
.HasKey(fs => new { fs.User1, fs.User2, fs.Status });

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User1)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User1);

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User2)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User2);
}
}



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!




When registering this as navigational property (see my code) then it will not be stored in db.



In other cases, if for some reason you don't want a property to be stored in db by ef core, mark the property with the [NotMapped] attribute (namespace System.ComponentModel.DataAnnotations.Schema).






share|improve this answer























  • not really, please read topic one more time
    – IchLiebeKadarka
    Nov 11 at 15:46










  • are you sure? I updated my example to match your problem. please check again.
    – B12Toaster
    Nov 11 at 16:02










  • i'm sorry but in meantime i have updated my post. now your example do same thinks like mine with attributes i think. but i dont know what should i do to have navigation property in Userclass, but to don't have additional field in database
    – IchLiebeKadarka
    Nov 11 at 16:08










  • give me a second will update my example [done]
    – B12Toaster
    Nov 11 at 16:16

















up vote
2
down vote



accepted










You can find one example in the official docs: https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many.



I adjusted this example to reflect your case:



namespace foo
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<UsersFriendship> UsersFriendships { get; set; }
}

public class Friendship
{
public User User1 { get; set; }
public int User1Id { get; set; }
public User User2 { get; set; }
public int User2Id { get; set; }
public int Status { get; set; }
}

class MyContext : DbContext
{
public DbSet<Friendship> Friendships { get; set; }
public DbSet<User> Users { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Friendship>()
.HasKey(fs => new { fs.User1, fs.User2, fs.Status });

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User1)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User1);

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User2)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User2);
}
}



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!




When registering this as navigational property (see my code) then it will not be stored in db.



In other cases, if for some reason you don't want a property to be stored in db by ef core, mark the property with the [NotMapped] attribute (namespace System.ComponentModel.DataAnnotations.Schema).






share|improve this answer























  • not really, please read topic one more time
    – IchLiebeKadarka
    Nov 11 at 15:46










  • are you sure? I updated my example to match your problem. please check again.
    – B12Toaster
    Nov 11 at 16:02










  • i'm sorry but in meantime i have updated my post. now your example do same thinks like mine with attributes i think. but i dont know what should i do to have navigation property in Userclass, but to don't have additional field in database
    – IchLiebeKadarka
    Nov 11 at 16:08










  • give me a second will update my example [done]
    – B12Toaster
    Nov 11 at 16:16















up vote
2
down vote



accepted







up vote
2
down vote



accepted






You can find one example in the official docs: https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many.



I adjusted this example to reflect your case:



namespace foo
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<UsersFriendship> UsersFriendships { get; set; }
}

public class Friendship
{
public User User1 { get; set; }
public int User1Id { get; set; }
public User User2 { get; set; }
public int User2Id { get; set; }
public int Status { get; set; }
}

class MyContext : DbContext
{
public DbSet<Friendship> Friendships { get; set; }
public DbSet<User> Users { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Friendship>()
.HasKey(fs => new { fs.User1, fs.User2, fs.Status });

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User1)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User1);

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User2)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User2);
}
}



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!




When registering this as navigational property (see my code) then it will not be stored in db.



In other cases, if for some reason you don't want a property to be stored in db by ef core, mark the property with the [NotMapped] attribute (namespace System.ComponentModel.DataAnnotations.Schema).






share|improve this answer














You can find one example in the official docs: https://docs.microsoft.com/en-us/ef/core/modeling/relationships#many-to-many.



I adjusted this example to reflect your case:



namespace foo
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<UsersFriendship> UsersFriendships { get; set; }
}

public class Friendship
{
public User User1 { get; set; }
public int User1Id { get; set; }
public User User2 { get; set; }
public int User2Id { get; set; }
public int Status { get; set; }
}

class MyContext : DbContext
{
public DbSet<Friendship> Friendships { get; set; }
public DbSet<User> Users { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Friendship>()
.HasKey(fs => new { fs.User1, fs.User2, fs.Status });

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User1)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User1);

modelBuilder.Entity<Friendship>()
.HasOne(fs => fs.User2)
.WithMany(u => u.UsersFriendships)
.HasForeignKey(fs => fs.User2);
}
}



the latest field comes from user class (UsersFriendships field) <-- and i dont want this field on my database!




When registering this as navigational property (see my code) then it will not be stored in db.



In other cases, if for some reason you don't want a property to be stored in db by ef core, mark the property with the [NotMapped] attribute (namespace System.ComponentModel.DataAnnotations.Schema).







share|improve this answer














share|improve this answer



share|improve this answer








edited yesterday

























answered Nov 11 at 10:47









B12Toaster

1,51811222




1,51811222












  • not really, please read topic one more time
    – IchLiebeKadarka
    Nov 11 at 15:46










  • are you sure? I updated my example to match your problem. please check again.
    – B12Toaster
    Nov 11 at 16:02










  • i'm sorry but in meantime i have updated my post. now your example do same thinks like mine with attributes i think. but i dont know what should i do to have navigation property in Userclass, but to don't have additional field in database
    – IchLiebeKadarka
    Nov 11 at 16:08










  • give me a second will update my example [done]
    – B12Toaster
    Nov 11 at 16:16




















  • not really, please read topic one more time
    – IchLiebeKadarka
    Nov 11 at 15:46










  • are you sure? I updated my example to match your problem. please check again.
    – B12Toaster
    Nov 11 at 16:02










  • i'm sorry but in meantime i have updated my post. now your example do same thinks like mine with attributes i think. but i dont know what should i do to have navigation property in Userclass, but to don't have additional field in database
    – IchLiebeKadarka
    Nov 11 at 16:08










  • give me a second will update my example [done]
    – B12Toaster
    Nov 11 at 16:16


















not really, please read topic one more time
– IchLiebeKadarka
Nov 11 at 15:46




not really, please read topic one more time
– IchLiebeKadarka
Nov 11 at 15:46












are you sure? I updated my example to match your problem. please check again.
– B12Toaster
Nov 11 at 16:02




are you sure? I updated my example to match your problem. please check again.
– B12Toaster
Nov 11 at 16:02












i'm sorry but in meantime i have updated my post. now your example do same thinks like mine with attributes i think. but i dont know what should i do to have navigation property in Userclass, but to don't have additional field in database
– IchLiebeKadarka
Nov 11 at 16:08




i'm sorry but in meantime i have updated my post. now your example do same thinks like mine with attributes i think. but i dont know what should i do to have navigation property in Userclass, but to don't have additional field in database
– IchLiebeKadarka
Nov 11 at 16:08












give me a second will update my example [done]
– B12Toaster
Nov 11 at 16:16






give me a second will update my example [done]
– B12Toaster
Nov 11 at 16:16




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53247895%2fef-core-one-to-many-or-many-to-many-users-friends%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

List item for chat from Array inside array React Native

Thiostrepton

Caerphilly