1

I have problem with saving many to many relationship. When I run the code, my mapping table "dbo.UserTown" does not have any data saved in this any idea why?

I have wrote my function for saving the users with lists of towns

  public void Save(User user)
    {
        context.User.Add(user);
        context.SaveChanges();
    }

My classes are like this:

public class User
{
    public long UserId { get; set; }
    public String Nickname { get; set; }
    [InverseProperty("Residents")]
    public virtual ICollection<Town> Residencies { get; set; }
}

and

public class Town
{
    public long TownId { get; set; }
    public String Name { get; set; }
    public virtual ICollection<User> Residents { get; set; }
}
cpoDesign
  • 8,953
  • 13
  • 62
  • 106

3 Answers3

0

You need to have mapping class

public class User
{
  public long UserId { get; set; }
  public String Nickname { get; set; }
  public virtual ICollection<TownResidents> TownResidents { get; set; }
}

public class Town
{
  public long TownId { get; set; }
  public String Name { get; set; }
  public virtual ICollection<TownResidents> TownResidents { get; set; }
}

public class TownResidents
{
  public long TownId { get; set; }
  public long UserId { get; set; }

  public virtual Town { get; set; } 
  public virtual User { get; set; } 
}
Asif Mushtaq
  • 13,010
  • 3
  • 33
  • 42
  • I am not sure that i do, as ef generate mapping table for me and i do not want to create new object and new table as EF allready does this for me. – cpoDesign May 22 '12 at 15:39
  • This is the right way, you can also check the question similar to yours. http://stackoverflow.com/questions/10690467/entityframework-mutli-table-many-to-many/10690570#10690570 – Asif Mushtaq May 22 '12 at 15:43
0

You don't have to create new entity to handle many to many relationships. First of all remove [InverseProperty("Residents")] . It's redundant. Your model is fine without it.

[InverseProperty("Entity")] is required if You are having more than one 'to many' relationships between Your entities.

I guess Your problem lays is how you are adding related data into entities. I think this article will help You out.

lucask
  • 2,290
  • 24
  • 19
0

Stange but i have discovered next day: I have done steps to clear problem:

  1. Fresh mug of coffe :)
  2. cleared all cashe in vs (clear all projects), Closed Visual Studio for sure
  3. Removed database
  4. Open VS and run project => this step created database
  5. Important: did NOT changed my code
  6. Run the project 2nd time to seed dummy data into system
  7. My table is populated.

Real headscratcher...

cpoDesign
  • 8,953
  • 13
  • 62
  • 106