簡體   English   中英

EF核心。 沒有更新導航屬性的更新實體

[英]EF Core. Update Entity without update navigation properties

我正在嘗試像這樣更新實體EF核心記錄:

public class Customer
{
    public int Id { get; set; }
    public int Name { get; set; }
    ...
    public int CountryId { get; set; }
    public virtual Country Country { get; set; }

    public int ZoneId { get; set; }
    public virtual Zone Zone { get; set; }

    public ICollection<Service> Services { get; set; }

    public virtual ICollection<Invoice> Invoices { get; set; }
}

當我調用Context.Update()或Context.Add()時,還要更新Zone和Country實體。 我不希望虛擬屬性更新。 我正在嘗試通過反射,獲取用於指示Entry(virtualProperty).State = EntityState.Detached的虛擬屬性,但我不能。 這是我正在嘗試的代碼。

Type typeOfTEntity = typeof(TEntity);
foreach (var property in typeOfTEntity.GetProperties())
{
    if (property.GetGetMethod().IsVirtual)
    {
        foreach (var member in context.Context.Entry(CurrentItem).Members)
        {
            if (member.Metadata.Name == property.Name)
            {
                context.Context.Entry(member).State = EntityState.Detached;
            }
        }
    }
}

我收到錯誤消息:“未找到實體類型'ReferenceEntry'。確保已將實體類型添加到模型中。” 我使用TEntity是因為我在通用類中使用了更多實體,並使用相同的方法來更新或添加。 提前致謝。

編輯:如果我使用非通用類型的實體(CurrentItem):(CurrentItem現在是Customer,而不是TEntity)

context.Context.Entry(CurrentItem.Country).State = EntityState.Detached;
context.Context.SaveChanges();

現在運作良好。 但是我需要使用TEntity。

我設法解決了這個問題。 不必在入口中插入屬性,而必須插入屬性的值。

using (var context = new OpenContext<TContext>(connectionString))
{
    var repository = context.UnitOfWork.GetRepository<TEntity, TKey>();
    repository.Update(CurrentItem);

    // Get the type of TEntity
    Type typeOfTEntity = typeof(TEntity);
    foreach (var property in typeOfTEntity.GetProperties())
    {
        // Check the properties that are virtual and not are HashSet
        if (property.GetGetMethod().IsVirtual && property.PropertyType.GenericTypeArguments.Count() == 0)
        {
            object value = property.GetValue(CurrentItem);
            // Check that value is not null and value type is an Entity
            if (value != null && value.GetType().IsSubclassOf(typeof(Entity<int>)))
            {
                // Set the value that I don't want to change
                context.Context.Entry(value).State = EntityState.Detached;
            }
        }
    }
    context.UnitOfWork.SaveChanges();
}

謝謝您的幫助。

如果您不想更新“實體”,那么當您獲得不願更新的客戶時,不應包括它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM