Browse Source

Add CheckAndSetId to AbpDbContext.

pull/96/head
Halil İbrahim Kalkan 9 years ago
parent
commit
6ba18a4945
  1. 28
      src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs
  2. 2
      src/Volo.Abp/Volo/Abp/Guids/SimpleGuidGenerator.cs

28
src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/AbpDbContext.cs

@ -1,4 +1,5 @@
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Threading;
@ -7,6 +8,8 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Guids;
using Volo.Abp.Reflection;
using Volo.Abp.Uow;
namespace Volo.Abp.EntityFrameworkCore
@ -14,10 +17,12 @@ namespace Volo.Abp.EntityFrameworkCore
public abstract class AbpDbContext<TDbContext> : DbContext
where TDbContext : DbContext
{
public IGuidGenerator GuidGenerator { get; set; }
protected AbpDbContext(DbContextOptions<TDbContext> options)
: base(options)
{
GuidGenerator = SimpleGuidGenerator.Instance;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
@ -91,6 +96,9 @@ namespace Volo.Abp.EntityFrameworkCore
{
switch (entry.State)
{
case EntityState.Added:
CheckAndSetId(entry);
break;
case EntityState.Modified:
case EntityState.Deleted:
HandleConcurrencyStamp(entry);
@ -109,5 +117,23 @@ namespace Volo.Abp.EntityFrameworkCore
entity.ConcurrencyStamp = Guid.NewGuid().ToString();
}
protected virtual void CheckAndSetId(EntityEntry entry)
{
//Set GUID Ids
var entity = entry.Entity as IEntity<Guid>;
if (entity != null && entity.Id == Guid.Empty)
{
var dbGeneratedAttr = ReflectionHelper
.GetSingleAttributeOrDefault<DatabaseGeneratedAttribute>(
entry.Property("Id").Metadata.PropertyInfo
);
if (dbGeneratedAttr == null || dbGeneratedAttr.DatabaseGeneratedOption == DatabaseGeneratedOption.None)
{
entity.Id = GuidGenerator.Create();
}
}
}
}
}

2
src/Volo.Abp/Volo/Abp/Guids/SimpleGuidGenerator.cs

@ -7,6 +7,8 @@ namespace Volo.Abp.Guids
/// </summary>
public class SimpleGuidGenerator : IGuidGenerator
{
public static SimpleGuidGenerator Instance { get; } = new SimpleGuidGenerator();
public virtual Guid Create()
{
return Guid.NewGuid();

Loading…
Cancel
Save