我使用实体框架6.1,现在我在项目中编写了一个数据层。有这样的课程
[Table("Name")]
public partial class Name
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
public string SecondName { get; set; }
[Required]
[StringLength(50)]
public string Patronymic { get; set; }
public virtual ICollection<Book> Books { get; set; }
public virtual ICollection<Profile> Profiles { get; set; }
}
和自动生成的存储库
public class NameRepository : INameRepository
{
NameContext context = new NameContext();
public IQueryable<Name> All
{
get { return context.Names; }
}
public IQueryable<Name> AllIncluding(params Expression<Func<Name, object>>[] includeProperties)
{
IQueryable<Name> query = context.Names;
foreach (var includeProperty in includeProperties) {
query = query.Include(includeProperty);
}
return query;
}
public Name Find(int id)
{
return context.Names.Find(id);
}
public void InsertOrUpdate(Name name)
{
if (name.Id == default(int)) {
// New entity
context.Names.Add(name);
} else {
// Existing entity
context.Entry(name).State = EntityState.Modified;
}
}
public void Delete(int id)
{
var name = context.Names.Find(id);
context.Names.Remove(name);
}
public void Save()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public interface INameRepository : IDisposable
{
IQueryable<Name> All { get; }
IQueryable<Name> AllIncluding(params Expression<Func<Name, object>>[] includeProperties);
Name Find(int id);
void InsertOrUpdate(Name name);
void Delete(int id);
void Save();
}
也会自动生成上下文。但是当我使用应用程序时
private static void Main(string[] args)
{
var name = new Name();
name.Books = new List<Book>();
name.FirstName = "max";
name.Patronymic = "A";
name.SecondName = "G";
name.Profiles = new List<Profile>();
var nameRepository = new NameRepository();
nameRepository.InsertOrUpdate(name);
nameRepository.Save();
var names = nameContext.All;
}
我没有数据库。但是这个应用程序运行并返回我的姓氏,我已经添加了。据我所知,如果数据库不存在,它可以由实体框架创建。但事实并非如此。所以我的问题是“如何创建这个数据库?”。但是,也许,我错了,实体框架无法创建数据库?