繁体   English   中英

实体框架上下文“未更新”?

[英]Entity Framework context “not freshed”?

平台:.net 内核 3.1 和 Oracle 11g。

这是我的 C# 代码片段:

// this puts the value "00000000-0000-00" in ExtRef
// On the database end, there's a before-insert trigger that overwrites this value
newCustomer.ExtRef = Guid.Empty.ToString().Substring(0, 16);

using CustomerContext cntxt =
    new CustomerContext(connectionStrings[MySchema]);

cntxt.Customer.Add(newCustomer);
cntxt.SaveChanges();

Customer saved =
    cntxt.Customer
         .AsQueryable()
         .Where(customer => customer.Name1 == newCustomer.Name1)
         .Single();

// Though the database reflects a new value for the ExtRef, this call still returns 00000000-0000-00
output.WriteLine($"{saved.ExtRef}");

我尝试使用上下文的新实例,并且 ExtRef 具有数据库中的值。 有没有一种方法可以在不使用第二个上下文的情况下获得更新的 ExtRef 值?

谢谢!

您想将实体中的 ExtRef 字段标记为DatabaseGenerated(DatabaseGeneratedOption.Computed) 这告诉 EF 期望在插入时设置该值,因此您可以在SaveChanges之后读取它。

public class Customer
{
    // ... 

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string ExtRef { get; set; } = "00000000-0000-00"; // Set a default here.
}

那么这应该可以按预期工作:

// newCustomer.ExtRef = Guid.Empty.ToString().Substring(0, 16); Not needed.

using CustomerContext cntxt = new CustomerContext(connectionStrings[MySchema])
{
    cntxt.Customer.Add(newCustomer);
    cntxt.SaveChanges();
}
output.WriteLine($"{newCustomer.ExtRef}");

暂无
暂无

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

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