English 中文(简体)
如何避免在伙伴关系中出现“实体类型xx”例外情况。 NET Core EF
原标题:How to avoid "The instance of entity type xx cannot be tracked" exception in ASP.NET Core EF Core

我在我的伙伴关系中遇到一个问题。 NET a. 与实体框架核心的核心应用,我一再收到以下答复:

{
  "statusCode": 500,
  "message": "The instance of entity type  Airline  cannot be tracked because another instance with the key value  {CarrierCode: DY}  is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached."
}

这发生在我<>PassengerController的“AddBaggage()”方法中的一种前方圆形:await_baggageRepository.AddAsync(NewBaggage);。 该方法:

[HttpPost("{id}/flight/{flightId}/add-baggage")]
        public async Task<ActionResult<Baggage>> AddBaggage(Guid id, int flightId,
            [FromBody] List<AddBaggageModel> addBaggageModels)
        {
            var passenger = await _passengerRepository.GetPassengerByIdAsync(id);
            var selectedFlight = await _flightRepository.GetFlightByIdAsync(flightId);
            var destination = await _destinationRepository.GetDestinationByCriteriaAsync(f =>
                f.IATAAirportCode == addBaggageModels.FirstOrDefault().FinalDestination);            

            var baggageList = new List<Baggage>();

            foreach (var baggageModel in addBaggageModels)
            {
                var newBaggage = new Baggage
                {
                    PassengerId = passenger.Id,
                    Weight = baggageModel.Weight,
                    DestinationId = destination.IATAAirportCode
                };

                //...some code
    
                else if (baggageModel.TagType == TagTypeEnum.System)
                {
                    var number = _baggageRepository.GetNextSequenceValue("BaggageTagsSequence");
                    var baggageTag = new BaggageTag(selectedFlight.ScheduledFlight.Airline, number);
                    newBaggage.BaggageTag = baggageTag;
                }

                await _baggageRepository.AddAsync(newBaggage); // An exception is thrown here, on the second iteration, when we attempt to assign a reference to the same object/instance of Airline as in the first iteration in the constructor parameter.            
                
                baggageList.Add(newBaggage);

                var orderedFlights = passenger.Flights
                    .Where(f => f.Flight.DepartureDateTime >= selectedFlight.DepartureDateTime)
                    .OrderBy(f => f.Flight.DepartureDateTime)
                    .ToList();

                foreach (var connectingFlight in orderedFlights)
                {
                    //...some code

                    FlightBaggage flightBaggage = new FlightBaggage
                    {
                        Flight = connectingFlight.Flight,
                        Baggage = newBaggage,
                        BaggageType = baggageType
                    };

                    newBaggage.Flights.Add(flightBaggage);

                    //...some code
                }
            }

            await _baggageRepository.UpdateAsync(baggageList.ToArray());

            return Ok();
        }

这里也是BagageTag建筑商之一:

        public BaggageTag(Airline? airline, int number)
        {
            Airline = airline;
            LeadingDigit = 0;
            Number = number;
            TagNumber = _GetBaggageTagNumber();
            TagType = TagTypeEnum.System;
        }

我在上还有以下法典。 页: 1

        public async Task<Flight> GetFlightByIdAsync(int id)
        {
            var CACHE_KEY = $"Flight_{id}";

            if (!_cache.TryGetValue(CACHE_KEY, out Flight flight))
            {
                flight = await _context.Flights.AsNoTracking()
                .Include(_ => _.ScheduledFlight)
                    .ThenInclude(_ => _.DestinationFrom)
                .Include(_ => _.ScheduledFlight)
                    .ThenInclude(_ => _.DestinationTo)
                .Include(_ => _.ScheduledFlight)
                    .ThenInclude(_ => _.Airline)
                .Include(_ => _.Aircraft)
                    .ThenInclude(_ => _.AircraftType)
                .Include(_ => _.Boarding)
                .Include(_ => _.ListOfBookedPassengers)
                    .ThenInclude(_ => _.Passenger)
                .Include(_ => _.ListOfCheckedBaggage)
                    .ThenInclude(_ => _.Baggage)
                .Include(_ => _.Seats)
                .FirstOrDefaultAsync(_ => _.Id == id);

                if (flight != null)
                {
                    _cache.Set(CACHE_KEY, flight, new MemoryCacheEntryOptions
                    {
                        SlidingExpiration = TimeSpan.FromMinutes(10)
                    });
                }
            }

            return flight;
        }
        public async Task<Passenger> GetPassengerByIdAsync(Guid id)
        {
            return await _context.Passengers.AsNoTracking()
                .Include(_ => _.PNR)
                .Include(_ => _.FrequentFlyer)
                .Include(_ => _.TravelDocuments)
                .Include(_ => _.PassengerCheckedBags)
                    .ThenInclude(_ => _.BaggageTag)
                .Include(_ => _.PassengerCheckedBags)
                    .ThenInclude(_ => _.SpecialBag)
                .Include(_ => _.Flights)
                    .ThenInclude(_ => _.Flight)
                        .ThenInclude(_ => _.ScheduledFlight)
                            .ThenInclude(_ => _.Airline)
                .Include(_ => _.Comments)
                    .ThenInclude(_ => _.PredefinedComment)
                .Include(_ => _.AssignedSeats)
                .Include(_ => _.SpecialServiceRequests)
                    .ThenInclude(_ => _.SSRCode)
                .FirstOrDefaultAsync(_ => _.Id == id);
        }

我的理解是,问题源于“变特拉克”试图吞并一个已经在此背景下追踪的实体。 然而,我不知道如何有效地避免这种情况。 I ve Read about detaching entities using dbContext.Entry(entity). 国家=实体国家。

我是否应在旅客存放处、飞行存放处或通用保存处等方法中加入,如AddAsync()、更新Async()和删除Async()? 或者,我是否在我的评议书中推翻了“拯救儿童协会”的方法,并将其列入?

我赞赏任何有效解决这一问题的指导或替代解决办法。 感谢你的帮助!

我试图从我的储存库中删除所有“NoTrack()”和“As Queryable()”方法,所有方法都非常有效。 然而,我最初增加了这些方法,以降低记忆的间接费用,从那时起,我一直面临这一问题。

问题回答

人们注意到几个问题,但主要嫌疑人是,贵方的存放方法是使用<条码>NoTracking(<>tTracking()(一.e. selectedFlight.SiguuledFlight.Airline)来收集数据,但你却试图将这些数据与这一图书和相关财产的新案例联系起来。 在装设相关实体时,你不想使用<代码>As NoTracking(<>>/code>,因为这将回馈一个新鲜的实体,如果Context,则可能已经追踪其他情况。 这可能产生与你所看到的错误,或由于指数限制而出现例外的情况,或用新的身份证插入重复记录。 (试图插入一个相关的不轨事件) 在请购查询中删除As NoTracking()可能会解决这个问题。

这是一个原因,我不建议采用保存方式,因为通过存放处发出的每一项要求都是对这一存放方法的单独关切。 有些电话可能需要相关数据,有些电话可能不需要。 选择一切可能非常昂贵,因此,“固定装置”可能是为了改进业绩而贴上)的标签,但这会导致出现意想不到的问题,因为像更新这样的其他代码预计会处理跟踪的参考资料。 如果编码使用在建的储存模式(DbSet),那么消费者可以更好地管理相关数据,以列入和优化专用操作的)。





相关问题
Entity Framework with MySQL connector in c#

I have been trying to get the Entity Framework to work in my web application using MySQL. It works fine on my local pc, but doesn t work when I put it on the server. Since the server is a shared ...

How Do I Create And Update A Many To Many Relationship With EF

I am using the Entity Framework with SQL Server. I have a many to many relationship between 2 tables. I have created a join table with just the primary key fields of the 2 tables. In the designer, the ...

Entity Framework with File-Based Database

I am in the process of developing a desktop application that needs a database. The application is currently targeted to SQL Express 2005 and works wonderfully. However, I m not crazy about having ...

Linq to enties, insert foreign keys

I am using the ADO entity framework for the first time and am not sure of the best way of inserting db recored that contain foreign keys. this is the code that i am using, I would appreciate any ...

Entity Framework - Many to many question

I have a table called ASB and a table called PeopleInvolved. There is a junction table called PeopleInvolved_ASB which simply contains an ASBID and a PeopleInvolvedID column. The columns act as a ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

ADO.NET Entity Data Model are not precise enough

I run this code: var cos = from k in _db.klienci_do_trasy where k.klient_id == 5 select k; but the query send to database is: SELECT * FROM `klienci_do_trasy` LIMIT 0, 30 why is it for, there ...