Adding values to “many to many ” relationship in entityframework

心不动则不痛 提交于 2019-12-04 07:13:36

问题


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
                     });


来源:https://stackoverflow.com/questions/16656783/adding-values-to-many-to-many-relationship-in-entityframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!