c# - 具有导航属性的 Entity Framework 继承

标签 c# entity-framework

我正在使用代码优先方法的 Entity Framework

enter image description here

但是我遇到了一些错误:

User: FromRole: NavigationProperty 'User' is not valid. Type 'SoteAccount' of FromRole 'User_SoteAccounts_Target' in AssociationType 'User_SoteAccounts' must exactly match with the type 'AllegroAccount' on which this NavigationProperty is declared on.
AllegroAccount_Template_Source: : Multiplicity is not valid in Role 'AllegroAccount_Template_Source' in relationship 'AllegroAccount_Template'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be ''.
SoteAccount_Template_Source: : Multiplicity is not valid in Role 'SoteAccount_Template_Source' in relationship 'SoteAccount_Template'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '
'.

甚至可以通过引用继承一个类吗?

这是类和onModelCreating

[Table("AllegroAccounts")]
public class AllegroAccount : ShopAccountBase
{
    public string AllegroLogin { get; set; }
    public string AllegroPassword { get; set; }
    public string AllegoWebApiKey { get; set; }
    public int CountryCode { get; set; }      
}

public class ShopAccountBase : AccountBase
{
    public int TemplateForeignKey { get; set; }
    [ForeignKey("TemplateForeignKey")]
    public Template Template { get; set; }
}

public abstract class AccountBase
{
    [Key]
    public int AccountBaseId { get; set; }
    public bool IsActive { get; set; }
    public int UserForeignKey { get; set; }
    [ForeignKey("UserForeignKey")]
    public virtual User User { get; set; }
    public bool DaysCountActive { get; set; }
    public int DaysCount { get; set; }
}

public class Template 
{
    public Template()
    {
        AdditionalServices = new AdditionalServices();
        BasicServices = new BasicServices();
        TemplatePackages = new ObservableCollection<TemplatePackage>();
    }

    [Key]
    public int TemplateID { get; set; }

    public string TemplateName { get; set; }
    public TemplateKind? TemplateKind { get; set; }
    public CourierFirm? CourierFirm { get; set; }
    public int Used { get; set; }
    public virtual ICollection<TemplatePackage> TemplatePackages { get; set; }
    public string ExternalNumber { get; set; }
    public string MPKNumber { get; set; }
    public AdditionalServices AdditionalServices { get; set; }
    public BasicServices BasicServices { get; set; }
    public string Description { get; set; }
    [Column(TypeName = "datetime")]
    public DateTime? CreationDate { get; set; }
}

public class User 
{
    public User() 
    {
        DefaultReturnAddress = new Address( );
        DefaultSendingAddress = new Address( );
        PersonInfoSending = new PersonInfo( );
        PersonInfoReturning = new PersonInfo( );
        AdditionalServices = new AdditionalServices( );

        WayBillLabel = new WaybillLabel( );
        Settings = new UserSettings( );
        AllegroAccounts = new ObservableCollection<AllegroAccount>();
        InpostAccounts = new ObservableCollection<InpostAccount>();
        TbaAccounts = new ObservableCollection<TbaAccount>();
        TruckerAccounts = new ObservableCollection<TruckerAccount>();
    }

    [Key]
    public int UserId { get; set; }

    public byte[] Password { get; set; }
    public string Login { get; set; }

    public Address DefaultReturnAddress { get; set; }
    public Address DefaultSendingAddress { get; set; }

    public PersonInfo PersonInfoSending { get; set; }
    public PersonInfo PersonInfoReturning { get; set; }

    public string MPKnumReturn { get; set; }
    public string MPKnumSending { get; set; }

    public AdditionalServices AdditionalServices { get; set; }

    public float MaxLength { get; set; }
    public float MaxWidth { get; set; }
    public float MaxHeight { get; set; }
    public float MaxWeight { get; set; }

    public int FileTemplateId { get; set; }
    public string CollectiveShipmentFilePath { get; set; }

    private PermissionFlags _permissions;

    public PermissionFlags Permissions
    {
        get { return _permissions; }
        set
        {
            if (_permissions.HasFlag(value)) { _permissions &= ~value; }
            else {
                _permissions |= value;
            }
        }
    }

    public TemplatingMethod TemplatingMethod { get; set; }

    public UserSettings Settings { get; set; }

    public WaybillLabel WayBillLabel { get; }

    public ICollection<AllegroAccount> AllegroAccounts { get; set; }
    public ICollection<SoteAccount> SoteAccounts { get; set; }

    public ICollection<InpostAccount> InpostAccounts { get; set; }
    public ICollection<TruckerAccount> TruckerAccounts { get; set; }
    public ICollection<TbaAccount> TbaAccounts { get; set; }

    // this is the right property to use for modifying the collection
    public ICollection<string> AvailableMpksCollection { get; set; }

    // this is computed property for Entity Framework only, because it cannot store a collection of primitive type
    public string AvailableMpksString
    {
        get { return AvailableMpksCollection != null ? string.Join(",", AvailableMpksCollection) : null; }
        set {
            AvailableMpksCollection = !string.IsNullOrEmpty(value) ? value.Split(',').ToList( ) : new List<string>( );
        }
    }
}


modelBuilder.Entity<AllegroAccount>().HasOptional(account => account.Template).WithOptionalDependent();

modelBuilder.Entity<User>()
            .HasMany<AllegroAccount>(u => u.AllegroAccounts)
            .WithOptional(acc => acc.User)
            .HasForeignKey(acc => acc.UserForeignKey);

modelBuilder.Entity<SoteAccount>().HasOptional(account => account.Template).WithOptionalDependent();

modelBuilder.Entity<User>()
            .HasMany<SoteAccount>(u => u.SoteAccounts)
            .WithOptional(acc => acc.User)
            .HasForeignKey(acc => acc.UserForeignKey);

有谁知道这是否可能或者我应该保持平坦而不是那样继承它?我问是因为这种继承很适合我的通用存储库模型

最佳答案

这可能是因为您正在定义 [ForeignKey] 属性并在流畅的配置中配置外键。

您已经在流畅的配置中定义了(AllegroAccount 和用户)和(SoteAccount 和用户)之间的链接,而您的 AccountBase 已经使用 [ForeignKey] 定义了此链接。

您的模板链接很可能也是如此 - 这种关系由 [ForeignKey] 属性在 ShopAccountBase 级别定义 - 您不需要在 fluent config 中为继承的类重新定义它。

尝试删除所有 modelBuilder 流畅的配置条目 - 它应该仍然可以通过继承关系工作。

关于c# - 具有导航属性的 Entity Framework 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36574738/

相关文章:

c# - 根据计数从字典列表中选择一个字典

c# - 如何在用户的电子邮件中发送购物项目

c# - 在数据库asp.net mvc中保存动态创建的控件数据

c# - Entity Framework Core 和 Cosmos DB。使用 LINQ 表达式读取实体

c# - MySQL - DbProviderFactory.CreateCommandBuilder 返回 null

mysql - 从实体类创建mysql数据库

c# - 为什么我从两个几乎相等的表达式中得到不同的结果以使用 Entity Framework 上下文从数据库中获取数据

c# - 在 EF Code First 中拥有计算字段的正确方法

c# - 是否可以扩展 Entity Framework 以添加新的数据库查询类型?

c# - 我如何验证第 3 方用户访问我的 Web API asp.net?