【问题标题】:Saving changes to eagerly loaded associations in RIA Services在 RIA 服务中保存对急切加载的关联的更改
【发布时间】:2023-03-27 06:19:02
【问题描述】:

我将 RIA 服务与实体框架一起用于我的 Silverlight 应用程序的数据层。我有两个以多对一关系相关的实体


public class Installation
{
    [Key]
    public string Serial { get; set; }
    public string Description { get; set; }
    [Column("District")]
    public Guid? DistrictID { get; set; }

    [Include]
    [Association("InstallationDistrict", "DistrictID", "DistrictID")]
    public District District { get; set; }
}

public partial class District
{
    [Key]
    public Guid DistrictID { get; set; }
    public string DisplayName { get; set; }
}

我正在为我的实体使用 EF Code First。

这是服务的代码:


[EnableClientAccess]
public class EagerLoadingService : DomainService
{
    private readonly CentralContext _context;
    public EagerLoadingService()
    {
        _context = new CentralContext();
    }
    [Query]
    public IQueryable GetInstallations()
    {
        return _context.Installations.Include("District");
    }
    [Update]
    public void UpdateInstallation(Installation i)
    {
        _context.Installations.Find(i.Serial).District = i.District;
        _context.SaveChanges();
    }
    [Query]
    public IQueryable GetDistricts()
    {
        return _context.Districts;
    }
}

加载安装时,我包含了相关的 District,它工作正常(我在客户端获取实体)。但是,当我在客户端更改 District 并尝试更新时,实体和服务上下文上的 HasChanged 标志仍然为 false,并且关联的外键不会更改(安装记录上的 DistrictID)。

有没有办法让它按照我期望的方式工作?

【问题讨论】:

  • 可能由于某种原因,各区正在分离。检查 EntityState 以获取您要保存的那个。
  • EntityState 未修改。也许这与我设置实体的方式有关。我将更新并添加有关实体类的更多详细信息。
  • 您正在修改的字段可能验证失败。尝试打开服务的生成代码文件(Generated_Code 文件夹)并在设置器中为该属性设置断点。
  • 感谢指向生成代码的指针。事实证明,如果属性中没有 IsForeignKey = true,它不会生成代码来设置实体的外键。

标签: c# entity-framework-4.1 wcf-ria-services


【解决方案1】:

原来我做的 Association 属性不正确。它必须是


[Association("InstallationDistrict", "DistrictID", "DistrictID", IsForeignKey = true)]

感谢this guide 指出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    相关资源
    最近更新 更多