這個賞金已經結束。此問題的答案有資格獲得 150聲望賞金。賞金寬限期在17 小時后結束。 Al2110想引起更多的關注這個問題。
我正在使用 Entity Framework Core 和 Sqlite 在 .NET 6 中創建 WPF 應用程式。
我有以下關系模型(請注意,為簡潔起見,省略了一些可為空的欄位):
[Table("Contacts")]
public class Contact
{
public Guid Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public ContactGroup? Parent { get; set; }
public Guid? ParentId { get; set; }
}
[Table("ContactGroups")]
public class ContactGroup
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public ContactGroup? Parent { get; set; }
public Guid? ParentId { get; set; }
public ObservableCollection<ContactGroup> SubGroups { get; set; } = new ObservableCollection<ContactGroup>();
public ObservableCollection<Contact> Contacts { get; set; } = new ObservableCollection<Contact>();
}//class
也就是說,aContactGroup可以有零個或多個Contacts。
我想將一些資料播種到 Sqlite 資料庫,其中一個聯系人屬于一個聯系人組,一個聯系人沒有父級,如下所示:
public class ContactsContext : DbContext
{
public DbSet<Contact> Contacts => Set<Contact>();
public DbSet<ContactGroup> ContactGroups => Set<ContactGroup>();
public ContactsContext()
{
Database.EnsureDeleted();
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=contacts.db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ContactGroup>(entity =>
{
entity.HasKey(x => x.Id);
entity.Property(x => x.Name);
entity.HasOne(x => x.Parent)
.WithMany(x => x.SubGroups)
.HasForeignKey(x => x.ParentId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Cascade);
entity.HasMany(x => x.Contacts);
});
Contact c1 = new Contact { Id = Guid.NewGuid(), Title = "Mr", FirstName = "John", LastName = "Smith" };
Contact c2 = new Contact { Id = Guid.NewGuid(), Title = "Mrs", FirstName = "Jane", LastName = "Doe" };
ContactGroup g1 = new ContactGroup { Id = Guid.NewGuid(), Name = "Social" };
g1.Contacts.Add(c1);
c1.Parent = g1;
c1.ParentId = g1.Id;
modelBuilder.Entity<ContactGroup>().HasData(
g1
);
modelBuilder.Entity<Contact>().HasData(
c1,
c2
);
}
}//class
嘗試從中創建遷移時,出現以下錯誤:
無法創建“ContactsContext”型別的物件
什么可能導致這種情況以及如何解決?
uj5u.com熱心網友回復:
在建構式中呼叫 EnsureCreated 和 EnsureDeleted 可能不是一個好主意。在我看來,這應該在某種 Startup.cs 檔案之外。把它移到外面......這樣,它可能會導致你的問題。
uj5u.com熱心網友回復:
Database.EnsureDeleted()并且Database.EnsureCreated()不應從建構式內部呼叫,而應在應在啟動時運行的方法中呼叫。
這是使用這些方法的典型方式:
public static void SetupContactsContext()
{
using (var context = new ContactsContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
}
上述方法應在啟動時呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511660.html
上一篇:默認表行/資料
