简体   繁体   English

实体框架多对多列表表关联

[英]Entity Framework Many to Many List Table Association

I have the following classes (I am only showing the properties that matter): 我有以下类(我仅显示重要的属性):

public class TypeLocation
{
    [Key]
    public int Id {get; set;}
    public string Country {get; set;}
    public string State {get; set;}
    public string County {get; set;}
    public string City {get; set;}

    public List<Offer> Offers {get; set; }
    public TypeLocation()
    {
        this.Offers = new List<Offer>();
    }
}

public class Offer
{
    public int Id { get; set; }

    public ICollection<TypeLocation> LocationsToPublish { get; set; }
}

This creates the following in the database: 这将在数​​据库中创建以下内容:

数据库架构

My Question/Problem 我的问题/问题

The TypeLocations table is prepopulated with a static list of country/state/county/city records, one or many of them can be associated with the Offer in LocationsToPublish property. TypeLocations表预先填充有国家/州/县/市/市记录的静态列表,其中一个或多个可以与LocationsToPublish属性中的Offer关联。 When I try to add a location, using the following code, Entity Framework adds a NEW record in the TypeLocation table and then makes the association by adding a record in the OfferTypeLocations table. 当我尝试使用以下代码添加位置时,Entity Framework将在TypeLocation表中添加NEW记录,然后通过在OfferTypeLocations表中添加记录来进行OfferTypeLocations

    public static bool AddPublishLocation(int id, List<TypeLocation> locations)
    {
        try
        {
            using (AppDbContext db = new AppDbContext())
            {
                Offer Offer = db.Offers
                    .Include("LocationsToPublish")
                    .Where(u => u.Id == id)
                    .FirstOrDefault<Offer>();

                //Add new locations
                foreach (TypeLocation loc in locations)
                {
                    Offer.LocationsToPublish.Add(loc);
                }
                db.SaveChanges();
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

I don't want a new record added to the TypeLocations table, just a relational record creating an association in the OfferTypeLocations table. 我不想要一个新的记录添加到TypeLocations表,只是一个关系记录创建的关联OfferTypeLocations表。 Any thoughts on what I am doing wrong? 对我在做什么错有任何想法吗?

Solution

Thanks to @Mick who answered below, I have found the solution. 感谢@Mick在下面回答,我找到了解决方案。

    public static bool AddPublishLocation(int id, List<TypeLocation> locations)
    {
        try
        {
            using (AppDbContext db = new AppDbContext())
            {
                Offer Offer = db.Offers
                    .Include("LocationsToPublish")
                    .Where(u => u.Id == id)
                    .FirstOrDefault<Offer>();

                //Add new locations
                foreach (TypeLocation loc in locations)
                {
                    //SOLUTION
                    TypeLocation ExistingLoc = db.AppLocations.Where(l => l.Id == loc.Id).FirstOrDefault<TypeLocation>();

                    Offer.LocationsToPublish.Add(loc);
                }
                db.SaveChanges();
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

What happens is, using the existing AppDbContext, I retrieve an existing record from the TypeLocations table (identified here as AppLocations ) and then Add it to the LocationsToPublish entity. 发生的事情是,使用现有的AppDbContext,我从TypeLocations表(在此标识为AppLocations )中检索了一条现有记录,然后将其添加到LocationsToPublish实体中。

The key is that I was to use the current AppDbContext (wrapped with the Using() statement) for all the work. 关键是我将使用当前的AppDbContext(与Using()语句包装在一起)进行所有工作。 Any data outside of this context is purely informational and is used to assist in the record lookups or creation that happen within the AppDbContext context. 此上下文之外的任何数据均纯粹是信息性的,可用于辅助AppDbContext上下文中发生的记录查找或创建。 I hope that makes sense. 我希望这是有道理的。

The TypeLocations are being loaded from a different AppDbContext, they are deemed new entities in the AppDbContext you're constructing within your method. TypeLocations是从其他AppDbContext加载的,它们被视为您在方法中构造的AppDbContext中的新实体。 To fix either:- 要解决这两个问题:

  1. Assuming the locations were detatched them from the instance of the AppDbContext outside of your method, you can attach these entities to the new context. 假设位置是从方法外部的AppDbContext实例中分离出来的,则可以将这些实体附加到新的上下文。 OR 要么
  2. Pass in the AppDbContext used to load the locations into your AddPublishLocation method. 传递用于将位置加载到您的AddPublishLocation方法中的AppDbContext。

I'd choose 2:- 我会选择2:-

public static bool AddPublishLocation(AppDbContext db, int id, List<TypeLocation> locations)
{
    try
    {
        Offer Offer = db.Offers
            .Include("LocationsToPublish")
            .Where(u => u.Id == id)
            .FirstOrDefault<Offer>();

        //Add new locations
        foreach (TypeLocation loc in locations)
        {
            Offer.LocationsToPublish.Add(loc);
        }
        db.SaveChanges();
        return true;
    }
    catch
    {
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM