第 2 部分问题,从这里继续:EntityFramework Core - Update record failed with DbUpdateConcurrencyException
错误:
派生类型“BinaryFile”不能在属性“Id”上具有 KeyAttribute,因为只能在根类型上声明主键。
我试图尽可能多地为我的实体进行继承,所以我尽可能地删除重复。
我的继承结构:
public interface IEntityMinimum
{
bool IsDeleted { get; set; }
byte[] Version { get; set; }
string CreatedBy { get; set; }
}
public class EntityMinimum : IEntityMinimum
{
public bool IsDeleted { get; set; }
[Timestamp]
public byte[] Version { get; set; }
public string CreatedBy { get; set; }
}
public interface IEntity : IEntityMinimum
{
object Id { get; set; }
DateTime CreatedDate { get; set; }
DateTime? ModifiedDate { get; set; }
string ModifiedBy { get; set; }
}
public interface IEntity<T> : IEntity
{
new T Id { get; set; }
}
public abstract class Entity<T> : EntityMinimum, IEntity<T>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public T Id { get; set; }
object IEntity.Id
{
get => Id;
set => throw new NotImplementedException();
}
private DateTime? _createdDate;
[DataType(DataType.DateTime)]
public DateTime CreatedDate
{
get => _createdDate ?? DateTime.UtcNow;
set => _createdDate = value;
}
[DataType(DataType.DateTime)]
public DateTime? ModifiedDate { get; set; }
public string ModifiedBy { get; set; }
}
public class EntityMaximum : Entity<int>
{
public bool IsActive { get; set; }
}
public class BinaryFile : EntityMaximum
{
public string Name { get; set; }
public string UniqueName { get; set; }
public Guid UniqueId { get; set; }
public byte[] Content { get; set; }
public virtual ICollection<Campaign> Campaigns { get; set; }
}
当我使用 Fluent API 禁用类isConcurrencyToken
的Version
字段时出现此错误,EntityMinimum
如下所示:
// https://stackoverflow.com/questions/44009020/entity-framework-isrowversion-without-concurrency-check
builder.Entity<EntityMinimum>().Property(x => x.Version).IsRowVersion().IsConcurrencyToken(false);
这是必需的,因为如果我不在现场禁用isConcurrencyToken
,我还有另一个问题Version
:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException:数据库操作预期影响 1 行,但实际影响 0 行。自加载实体以来,数据可能已被修改或删除。
如果我删除 fluent api 配置,它可以工作,但由于Version
具有[TimeStamp]
属性的字段而不会更新。
我将此[TimeStamp]
Version
字段EntityMinimum
附加Version
到每个表中,因此我可以TimeStamp
用于移动和 Web 数据之间的同步目的。
我是否正确地执行此结构,还是应该摆脱[TimeStamp] byte[] Version
并仅使用字符串Version
并将DateTime
刻度保存到其中以进行同步?
问题是调用
builder.Entity<EntityMinimum>()
将EntityMinimum
类标记为实体(EF Core 继承策略的一部分),而据我所知,您使用基类层次结构只是为了实现目的。
相反,您可以使用 EF Core 模型元数据服务来关闭派生自如下的任何真实实体IsConcurrencyToken
的Version
属性EntityMinimum
:
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (typeof(EntityMinimum).IsAssignableFrom(entityType.ClrType))
entityType.FindProperty("Version").IsConcurrencyToken = false;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句