Does Entity Framework 4 Code First have support for identity generators like NHibernate?

前端 未结 3 1312
暖寄归人
暖寄归人 2020-11-27 07:57

This question, asked a year ago, is similar: Does the Entity Framework 4 support generators for id values like NHibernate?

But what I\'d like to know is if the code

相关标签:
3条回答
  • 2020-11-27 08:01

    No, Entity framework code-first is still just nice wrapper around EFv4. There are no NHibernate like generators. If you want client side Id generator you will have to override SaveChanges in derived DbContext and implement your own logic of assigning Ids to new entities.

    Edit:

    Some high level example:

    public class Context : DbContext
    {
        // Helper for example
        // DO NOT USE IN REAL SCENARIOS!!!
        private static int i = 0; 
    
        public DbSet<MyEntity> MyEntities { get; private set; }
    
        public Context()
            : base("connection")
        {
            MyEntities = Set<MyEntity>();
        }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity<MyEntity>().HasKey(e => e.Id);
            // Turn off autogeneration in database
            modelBuilder.Entity<MyEntity>()
                        .Property(e => e.Id)
                        .HasDatabaseGeneratedOption(HasDatabaseGeneratedOption.None);
    
            // Other mapping
        }
    
        public override int SaveChanges()
        {
            foreach (var entry in ChangeTracker.Entries<MyEntity>()
                .Where(e => e.State == EntityState.Added))
            {
                // Here you have to add some logic to generate Id
                // I'm using just static field
                entry.Entity.Id = ++i;  
            }
    
            return base.SaveChanges();
        }
    }
    
    public class MyEntity
    {
        public int Id { get; set; }
        // Other properties
    }
    
    0 讨论(0)
  • 2020-11-27 08:10

    No.

    Mine Entity Framework 4.1.10715 installed by NuGet. maybe you could use attribute

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id {get;set;}
    

    please see (The full list of annotations supported in EF 4.1 : CTRL+F in page) here.

    0 讨论(0)
  • 2020-11-27 08:12
    [Key]
    public string Id { get; set; }
    

    and then use new GUID ToString

    Units.Add( new Unit(){Id=Guid.NewGuid().ToString(), Name="123"});
    
    0 讨论(0)
提交回复
热议问题