Adding values to “many to many ” relationship in e

2019-03-03 17:08发布

问题:

I have 3 entities in Sqlserver that I am mapping with the wizard of visual Studio

The three entities are packages categories and packages_categories,where packages_categories an many to many relationship. After mapping These entities I am geting 2 classes wich are Categories and Packages,they look like this: public partial class Package { public Package() { this.Categories = new HashSet(); }

    public string PackageSid { get; set; }
    public string PackageName { get; set; }

    public virtual ICollection<Category> Categories { get; set; }
} 

public partial class Category { public Category() { this.Packages = new HashSet(); }

    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public bool isDefault { get; set; }

    public virtual ICollection<Package> Packages { get; set; }
}

and I am getting nothing for the entity of the many to many relationship(this one of packages_categories) the hall Thing works great when I try to get info from packages for example then every time i try to query a packages i get ist packages with it and the same Thing when i try to get packages of categories.

The Problem is when i try to update a package and add categories to it then the category will be added not just to the entitiy packages_categories but also to categories self

An example for code :

var categoriesList=List<Categoriy>();


categoriesList.Add(new Cateogry{
                    categoryname="catem",
                    IsDefault=false,
                    CategoryId=2332

});

var _packagesContext=new DBPackages();
_packagesContext.Add(new Packages{
                      packageSid="Sid blaaa.",
                      PackageName="TestPackage",
                      Categories=categoriesList
                           });

Now in this code a package with one category will be added to the database,but if the category already there an exception will be thrown that a the category is already there(lets suppose it is already there,this means it tries to add it to Categories self),

How can i solve a Problem like this?? what am I doing wrong :( Thanx very much.

回答1:

In order to avoid creating new categories you must attach them to the context before you add the new package:

var _packagesContext=new DBPackages();

categoriesList.ForEach(c => _packagesContext.Categories.Attach(c));

_packagesContext.Add(new Packages {
                         packageSid="Sid blaaa.",
                         PackageName="TestPackage",
                         Categories=categoriesList
                     });