簡體   English   中英

實體框架-使用類繼承創建模型

[英]Entity Framework - Model creation using class inheritance

嘗試通過代碼優先實體框架6.1使用繼承創建模型對象時遇到一個奇怪的問題。

我已經在共享代碼庫中創建了一個基礎User類,在我的應用程序中,我還創建了另一個繼承自該基礎類的User類。

基本用戶類別:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using CSAMLib.Data.Entity;
using CSAMLib.Security.Cryptography;
using System.ComponentModel.DataAnnotations;

namespace CSAMLib.Security
{
    public class User : BaseEntity, CSAMLib.Security.IUser
    {
        public bool Active { get; set; }

        [Display(Name = "First name")]
        public String FirstName { get; set; }

        [Display(Name = "Last name")]
        public String LastName { get; set; }

        [Display(Name = "Full name")]
        public String FullName { get { return (FirstName == null ? String.Empty : FirstName + " ") + (LastName ?? String.Empty); } }

        [Display(Name = "Login", Prompt = "someone@example.com")]
        public String Login { get; set; }

        [Display(Name = "Email address")]
        public String EmailAddress { get; set; }

        public byte[] Password { get; set; }

        [Display(Name = "Last login date")]
        public DateTime? LastLoginDate { get; set; }

        [Display(Name = "Logged in")]
        public bool CurrentlyLoggedIn { get; set; }

        [Display(Name = "Signature filepath")]
        public byte[] SignatureFileContent { get; set; }

        [Display(Name = "Signature filename")]
        public String SignatureFileName { get; set; }

        [Display(Name = "Signature content")]
        public String SignatureContentType { get; set; }

        public String Qualification { get; set; }

        [NotMapped]
        public String NewPassword { get; set; }
        [NotMapped]
        public PasswordPolicy PasswordPolicy { get; set; }

        public virtual ICollection<UserRole> UserRoles
        {
            get;
            set;
        }

        public byte[] Salt { get; set; }

    }
}

用戶類別:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace Muro.Models
{
    [Table("Users")]
    public class User : CSAMLib.Security.User
    {
        public bool ClientUser { get; set; }

        [Display(Name = "Company")]
        [ForeignKey("Company")]
        public Int64? CompanyID { get; set; }
        public virtual Company Company { get; set; }

        public new ICollection<UserRole> UserRoles
        {
            get;
            set;
        }


        public SystemUser CreateNewUser(string userName, string emailAddress, string firstName, string lastName)
        {
            var user = new Muro.Models.User();
            user.Login = userName;
            user.EmailAddress = emailAddress;
            user.Active = false;
            user.CurrentlyLoggedIn = false;
            user.FirstName = firstName;
            user.LastName = lastName;
            return user;
        }
    }

DBContext:

public DbSet<Muro.Models.User> Users { get; set; }

運行更新數據庫時,此方法導致以下錯誤:

類型“ CSAMLib.Security.User”和類型“ Muro.Models.User”都具有相同的簡單名稱“ User”,因此不能在同一模型中使用。 給定模型中的所有類型都必須具有唯一的簡單名稱。 使用“ NotMappedAttribute”或在Code First fluent API中調用“忽略”以從模型中明確排除屬性或類型。

我可以理解這一點,因為兩個類名都共享簡單名稱。 我的下一個方法是將應用程序User類重命名為SystemUser,以解決此問題。 但是,我現在遇到以下錯誤,並且不確定接下來要去哪里。

錯誤:

System.InvalidOperationException: Sequence contains more than one element
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at System.Data.Entity.ModelConfiguration.Conventions.ForeignKeyPrimitivePropertyAttributeConvention.Apply(PropertyInfo memberInfo, ConventionTypeConfiguration configuration, ForeignKeyAttribute attribute)
   at System.Data.Entity.ModelConfiguration.Conventions.PropertyAttributeConfigurationConvention`1.<.ctor>b__0(ConventionTypeConfiguration ec)
   at System.Data.Entity.ModelConfiguration.Conventions.TypeConvention.ApplyCore(Type memberInfo, ModelConfiguration modelConfiguration)
   at System.Data.Entity.ModelConfiguration.Conventions.TypeConventionBase.Apply(Type memberInfo, ModelConfiguration modelConfiguration)
   at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
   at System.Data.Entity.ModelConfiguration.Conventions.Convention.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
   at System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModelConfiguration(Type type, ModelConfiguration modelConfiguration)
   at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
   at System.Data.Entity.ModelConfiguration.Mappers.NavigationPropertyMapper.Map(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
   at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
   at System.Data.Entity.ModelConfiguration.Mappers.NavigationPropertyMapper.Map(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
   at System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
   at System.Data.Entity.DbModelBuilder.<>c__DisplayClassd.<MapTypes>b__7(Type type)
   at System.Linq.Enumerable.WhereListIterator`1.MoveNext()
   at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
   at System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model)
   at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
   at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
   at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
   at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1 writeXml)
   at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains more than one element

SystemUser類:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace Muro.Models
{
    [Table("Users")]
    public class SystemUser : CSAMLib.Security.User
    {
        public bool ClientUser { get; set; }

        [Display(Name = "Company")]
        [ForeignKey("Company")]
        public Int64? CompanyID { get; set; }
        public virtual Company Company { get; set; }

        public new ICollection<SystemUserRole> UserRoles
        {
            get;
            set;
        }


        public SystemUser CreateNewUser(string userName, string emailAddress, string firstName, string lastName)
        {
            var user = new Muro.Models.SystemUser();
            user.Login = userName;
            user.EmailAddress = emailAddress;
            user.Active = false;
            user.CurrentlyLoggedIn = false;
            user.FirstName = firstName;
            user.LastName = lastName;
            return user;
        }
    }
}

DBContext:

public DbSet<SystemUser> Users { get; set; }

有沒有人看到過相同的行為,並有解決此問題的提示?

謝謝!

我認為第一個問題與第二個問題無關(因為您已經解決了)。

異常告訴您問題應該是什么:
您在一個似乎有一個以上項目的集合上調用SingleOrDefault() ,這是該方法所不允許的。 您可以執行以下操作來解決此問題:

  • 使用FirstOrDefault獲取集合匹配的第一個元素
  • 調整搜索模式,使其僅返回零或一個元素

如果您向我們顯示對SingleOrDefault的實際調用,我們可能會更好地為您提供幫助,但在發布的代碼中找不到這樣的調用...

這是因為您的類具有[Table()]屬性的相同值,盡管您重命名了類,但是您仍試圖創建兩個具有相同名稱的表,這導致“序列包含多個元素”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM