gpt4 book ai didi

angularjs - 如何添加丢失的外键/实体?使用 JObjects 保存 BreezeJs

转载 作者:行者123 更新时间:2023-12-02 22:27:19 25 4
gpt4 key购买 nike

这是首先使用实体​​框架 6 和延迟加载的数据库。我有以下类别的设备缺少四个外键 ID:

public partial class Device {
public int SolutionId { get; set; }
public string SiteId { get; set; }
public string Name { get; set; }
public int SysId { get; set; }
public Nullable<int> SysType { get; set; }
public string SerialNumber { get; set; }
public Nullable<int> ParentId { get; set; }

public virtual DeviceModel DeviceModel { get; set; }
public virtual DeviceType DeviceType { get; set; }
public virtual SolutionApplication SolutionApplication { get; set; }
public virtual SolutionType SolutionType { get; set; }
}

未生成但自动映射为虚拟对象的缺失键/ID:

DeviceModelId, DeviceTypeId, SolutionApplicationId, and SolutionTypeId

我想使用 Breeze 保存一个新设备,但它正在寻找设备类型。我尝试在保存之前添加 deviceTypeId:

newDevice.deviceTypeId = 5;

但它仍然没有被读取,也没有被保存。

[Error] Save failed: Entities in 'PortalEntities.Devices' participate in the 'FK_Devices_DeviceTypes' relationship. 0 related 'DeviceType' were found. 1 'DeviceType' is expected.

这就是我在 Breeze Controller 中的保存语句:

    [HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _repository.SaveChanges(saveBundle);
}

我检查了当它尝试保存时实际传递的内容。捆绑的保存包含以下实体。但作为必填字段的设备类型不存在,因此会出现缺少该字段的错误。

"entities": [
{
"SolutionId": -1,
"SiteId": "11111d2",
"Name": "asdf",
"SysId": 0,
"SysType": null,
"SerialNumber": null,
"ParentId": null,
"entityAspect": {
"entityTypeName": "Device:#HtPortal.Data.Portal",
"defaultResourceName": "Devices",
"entityState": "Added",
"originalValuesMap": {},
"autoGeneratedKey": {
"propertyName": "SolutionId",
"autoGeneratedKeyType": "Identity"
}
}
}

由于 deviceTypeId 不起作用,所以我尝试在保存之前添加 deviceType:

newDevice.deviceType = { id:5, name: 'Blue'}; //NOTE: This already exists in the devicetype table in the database

但我收到以下错误:

TypeError: Cannot read property 'entityState' of undefined

使用 Breeze,如何添加这个外部实体以便我可以保存这个新设备?

编辑 1:这是我的 DeviceType 类:

    public partial class DeviceType {
public DeviceType() {
this.Devices = new HashSet<Device>();
}

public byte Id { get; set; }
public string Name { get; set; }

public virtual ICollection<Device> Devices { get; set; }
}

最佳答案

只需从 dbContext 添加现有的 DeviceType 对象即可。

类似于:

using (YourDbEntities context = new YourDbEntities())
{
Device newDevice = new Device();

//whatever initialisation you need do....

newDevice.DeviceType = context.DeviceTypes.Find(5)

// the above line assumes that id is PK for DeviceType and you want the entry
// with id==5 - if not, other ways such as DeviceTypes.Where(d=>d.Id==5).First()
// to find the object in your existing db will work too!

context.Devices.Add(newDevice);
context.SaveChanges();
}

关于angularjs - 如何添加丢失的外键/实体?使用 JObjects 保存 BreezeJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26720959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com