我对EF(使用EF core 2.1)非常陌生,到目前为止一直在跟随一堆教程学习,但现在我已经开始创建自己的数据库结构,并在尝试将值添加到数据库时遇到了问题:
private async Task<int> Insert()
{
var address = new Address { AddressLine1 = "1 any street", AddressLine2 = "", AddressLine3 = "", City = "Any city" };
using (var context = new BranchContext())
{
context.Addresses.AddAsync(address);//ERROR HERE
....
}
}
我遇到了以下错误:
InvalidOperationException: 属性“Branch.Address”是类型为“Address”的,当前数据库提供程序不支持。要么更改属性CLR类型,要么使用“[NotMapped]”属性或在“OnModelCreating”中使用“EntityTypeBuilder.Ignore”忽略该属性。
我创建了以下类:
public class Address
{
public int Id { get; set; }
public int Guid { get; set; }
public DateTime CreatedOn { get; set; }
public string Number { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string Town { get; set; }
public string City { get; set; }
public string Postcode1 { get; set; }
public string Postcode2 { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
}
public class Branch
{
public string Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
public IEnumerable<EmployeeBranch> Employee { get; set; }
public bool IsMain { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Guid { get; set; }
public string EmailAddress { get; set; }
public JobTitle JobTitle { get; set; }
public DateTime DateOfBirth { get; set; }
public IEnumerable<EmployeeBranch> Branches { get; set; }
public Branch PrimaryBranch { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PreferredName { get; set; }
public Salutations Salutation { get; set; }
}
public enum Salutations
{
Mr = 1,
Mrs = 2,
Miss = 3,
Ms = 4
}
public class EmployeeBranch
{
public int BranchId { get; set; }
public Branch Branch { get; set; }
public int EmployeeId { get; set; }
public Employee Employee { get; set; }
}
public class JobTitle
{
public int Id { get; set; }
public string Guid { get; set; }
public string Name { get; set; }
}
然后我运行了:
Add-Migration init
Update-Database
以下内容是创建的:
![DB structure](https://istack.dev59.com/Pb8yR.webp)
如何解决这个问题?最好不要更改结构,尽管如果有充分的理由可以这样做,我也很乐意。