Entity framework 实体框架、种子和标识
我需要在数据库中创建一些虚拟记录,但当我使用下面的代码填充数据库时,它不会创建任何内容 我没有收到任何错误,并且可以看到seed方法正在运行 我怀疑它与身份和自动增量或其他东西有关,但我不太确定 我有一些递归表和表之间的关系,所以如何在种子方法中处理这些关系Entity framework 实体框架、种子和标识,entity-framework,ef-code-first,Entity Framework,Ef Code First,我需要在数据库中创建一些虚拟记录,但当我使用下面的代码填充数据库时,它不会创建任何内容 我没有收到任何错误,并且可以看到seed方法正在运行 我怀疑它与身份和自动增量或其他东西有关,但我不太确定 我有一些递归表和表之间的关系,所以如何在种子方法中处理这些关系 namespace CalMeser.Data.Sql.Migrations { using System.Collections.Generic; using System.Data.Entity.Migratio
namespace CalMeser.Data.Sql.Migrations
{
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Diagnostics.Contracts;
using CalMeser.Data.Entities;
[ContractVerification(false)]
internal sealed class Configuration : DbMigrationsConfiguration<DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(DataContext context)
{
context.Tags.AddOrUpdate(new Tag
{
Name = "Computers",
Sort = 1,
Children = new List<Tag>
{
new Tag
{
Name = "Computer Science",
Sort = 1,
Children = new List<Tag>
{
new Tag
{
Name = "Programming",
Sort = 4
},
new Tag
{
Name = "Security",
Sort = 2
},
new Tag
{
Name = "Algorithms",
Sort = 3
},
new Tag
{
Name = "Data Structures",
Sort = 1
},
}
},
new Tag
{
Name = "Computer Information Systems",
Sort = 2
},
new Tag
{
Name = "Computer Engineering",
Sort = 3
}
}
});
context.Tags.AddOrUpdate(new Tag
{
Name = "Nature",
Sort = 1,
Children = new List<Tag>
{
new Tag
{
Name = "Animals",
Sort = 3,
Children = new List<Tag>
{
new Tag
{
Name = "Cats",
Sort = 1
},
new Tag
{
Name = "Dogs",
Sort = 2
},
new Tag
{
Name = "Fish",
Sort = 3
},
new Tag
{
Name = "Monkeys",
Sort = 4
},
}
},
new Tag
{
Name = "Plants",
Sort = 2,
Children = new List<Tag>
{
new Tag
{
Name = "Mint",
Sort = 1
},
new Tag
{
Name = "Sage",
Sort = 2
},
new Tag
{
Name = "Lime",
Sort = 3
}
}
},
new Tag
{
Name = "Space",
Sort = 1
}
}
});
context.SaveChanges();
}
}
}
下面是上面代码中使用的实体
namespace CalMeser.Data.Abstractions
{
public abstract class Entity : IEntity
{
public long Id { get; set; }
}
}
namespace CalMeser.Data.Abstractions
{
using System.Collections.Generic;
public abstract class RecursiveEntity<TEntity> : Entity where TEntity : RecursiveEntity<TEntity>
{
public virtual IList<TEntity> Children { get; set; }
public virtual TEntity Parent { get; set; }
public long? ParentId { get; set; }
}
}
namespace CalMeser.Data.Entities
{
using CalMeser.Data.Abstractions;
public class Tag : RecursiveEntity<Tag>
{
public File Image { get; set; }
public string Name { get; set; }
public long Sort { get; set; }
}
}
嗯,我决定放弃自动递增,转而使用顺序Guid梳,这样我就可以预先计算值并自己初始化它 这里有几篇文章和帖子帮助我做出这个决定