【问题标题】:EF Inserting data but all GUID turn to same with each otherEF插入数据但所有GUID彼此相同
【发布时间】:2021-03-26 17:19:09
【问题描述】:
if (tubeCodes.Count > 0) 
{
    foreach (var item in tubeCodes)
    {
        PrepLabSampleTubeVol entity = new PrepLabSampleTubeVol()
                    {
                        SampleId = sample.SampleId,
                        TubeCode = item,
                        Volume = sample.Vol==null ? 0:sample.Vol,
                        VersionNo = 0,
                        TransactionID = Guid.NewGuid(),
                        CreatedBy = CurrentUserInfo.LabName,
                        CreatedDttm = DateTime.Now,
                        UpdatedBy = CurrentUserInfo.LabName,
                        UpdatedDttm = DateTime.Now,
                    };
        tubeVolumnList.Add(entity);
    }
}

using (var uow = new UnitOfWork(db))
{
    tubeVolumnList.ForEach(x => uow.Repository<PrepLabSampleTubeVol>().Insert(x));
    //uow.Repository<PrepLabSampleTubeVol>().BulkInsert(tubeVolumnList);
    uow.Repository<PrepLabSample>().Update(sample);
    uow.Save();

    return true;
}

当我为每个项目生成TransactionID 时,它们彼此不同,但是当代码去插入时,所有项目的TransactionID 都变成了相同的。在数据库中,TransactionID是表的主键。

public partial class PrepLabSampleTubeVol:EntityBase,GWZ.Lab.Entity.IAuditableEntity
{
    public Nullable<System.Guid> SampleId { get; set; }
    public string TubeCode { get; set; }
    public Nullable<decimal> Volume { get; set; }
    public int VersionNo { get; set; }

    [Key]
    public System.Guid TransactionID { get; set; }

    public string CreatedBy { get; set; }
    public System.DateTime CreatedDttm { get; set; }
    public string UpdatedBy { get; set; }
    public System.DateTime UpdatedDttm { get; set; }
}

异常信息:

快速观看:

【问题讨论】:

  • EF 可能假设数据库将生成新的 GUID?你能发布类和模型构建定义吗?
  • 更新了,请看。
  • 是的,对于 Guid & int 键的 EF 将假定 db 将生成一个值。 (EF 核心还是 EF 6??)docs.microsoft.com/en-us/ef/core/modeling/…

标签: c# .net asp.net-mvc entity-framework linq


【解决方案1】:

要在代码中设置 ID 列,您必须将 EF 配置为期望生成 ID。这是通过DatabaseGeneratedOption.None完成的

[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public System.Guid TransactionID { get; set; }

对于 GUID ID,强烈建议允许数据库生成 ID 并使用顺序 UUID,而不是更随机的格式。假设 SQL Server 将使用默认值 NewSequentialId() 而不是 NewId() 定义 TransactionId,并使用以下内容配置实体:

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public System.Guid TransactionID { get; set; }

如果您确实需要在代码中分配 ID,则建议生成适合 UUID 的数据库存储的可排序 GUID。例如,对于 SQL Server 并使用 .Net Core,您可以使用 SequentialGuidValueGenerator 类:https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.valuegeneration.sequentialguidvaluegenerator?view=efcore-5.0。有一些例子可以写你自己的。对于其他数据库,您可能需要使用不同的生成器算法,具体取决于索引对 128 位值的排序方式。您希望使用可排序 UUID 的原因是减少在针对 UUID 列构建聚集索引等内容时可能发生的索引碎片。这可能会导致索引表的大小爆炸,从而损害性能并需要频繁的索引维护操作来控制索引。

【讨论】:

    猜你喜欢
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    相关资源
    最近更新 更多