我正在为我的公司建立一个概念验证。我们有一个现有的平台,将逐步使用现代技术进行替换。目前,我只能使用我们现有的数据库,其中有几个无关键字的表格。我正在构建一个Blazor WebAssembly应用程序,该应用程序使用gRPC调用到一个.NET Core Web应用程序。我的问题是我正在使用EF Core与现有数据库通信,但在调用DbContext.Attach(shipment)
时出现异常。
"The navigation '' cannot be added because it targets the keyless entity type 'Document'. Navigations can only target entity types with keys."
Document
是实体类在DbContext
中被 Attach
的一个导航属性。
Shipment
是一个非常庞大且具有多层结构的数据结构。是否有一种避免在模型结构中为每个实体设置实体状态(DbContext.Entry(entity).State = EntityState.Added
)的方法?或者可能将DbSet的CRUD操作映射到存储过程中? 编辑 这里是一个极度缩短版本的模式,但这就是问题所在的全部内容。
public class Shipment
{
public int Id { get; set; }
// 60 other properties
public virtual ICollection<Document> Documents { get; set; }
}
public class Document
{
public int ShippingId { get; set; }
public string DocumentType { get; set; }
public byte[] Content { get; set; }
public virtual Shipment Shipment { get; set; }
}
当我尝试将
Shipment
实体附加到DbContext
或手动设置其状态时,我会收到上面的异常。再次说明,我现在无法更改数据库架构,并且有许多其他与
Document
类似但没有关键字或添加关键字的模型。编辑2:
我意识到这需要进一步解释。显然,
DbContext
不能插入/更新/删除,因为没有键,它不知道如何操作。我只需要在获取Shipping
实体并设置导航属性Documents
时能够读取即可。但是,在保存Shipping
时,完全忽略导航属性。
[Key]
将属性标识为主键。 - LinkedListT