该类型已配置为实体类型。它不能重新配置为复杂类型

时间:2015-12-28 13:07:08

标签: c# .net entity-framework

我不知道为什么,但我在ctx.Database.Initialize(false)

收到此错误

异常详情(bij = at)

System.InvalidOperationException was unhandled
HResult=-2146233079
Message=The type 'Contact' has already been configured as an entity type. It cannot be reconfigured as a complex type.
Source=EntityFramework
StackTrace:
   bij System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ComplexType(Type complexType)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<>c__DisplayClass9.<MapComplexType>b__6()
   bij System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.<>c__DisplayClass2.<MapPrimitiveOrComplexOrEnumProperty>b__0()
   bij System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.PropertyConfigurationConventionDispatcher.<Dispatch>b__f[TPropertyConfiguration]()
   bij System.Data.Entity.ModelConfiguration.Configuration.ConventionPrimitivePropertyConfiguration.IsRequired()
   bij System.Data.Entity.ModelConfiguration.Conventions.RequiredPrimitivePropertyAttributeConvention.Apply(ConventionPrimitivePropertyConfiguration configuration, RequiredAttribute attribute)
   bij System.Data.Entity.ModelConfiguration.Conventions.PrimitivePropertyAttributeConfigurationConvention`1.<.ctor>b__0(ConventionPrimitivePropertyConfiguration configuration, IEnumerable`1 attributes)
   bij System.Data.Entity.ModelConfiguration.Conventions.PropertyConventionWithHaving`1.ApplyCore(PropertyInfo memberInfo, Func`1 configuration, ModelConfiguration modelConfiguration)
   bij System.Data.Entity.ModelConfiguration.Conventions.PropertyConventionBase.Apply(PropertyInfo memberInfo, Func`1 configuration, ModelConfiguration modelConfiguration)
   bij System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.PropertyConfigurationConventionDispatcher.Dispatch[TPropertyConfiguration]()
   bij System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.PropertyConfigurationConventionDispatcher.Dispatch()
   bij System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyPropertyConfiguration(PropertyInfo propertyInfo, Func`1 propertyConfiguration, ModelConfiguration modelConfiguration)
   bij System.Data.Entity.ModelConfiguration.Conventions.Convention.ApplyPropertyConfiguration(PropertyInfo propertyInfo, Func`1 propertyConfiguration, ModelConfiguration modelConfiguration)
   bij System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyPropertyConfiguration(PropertyInfo propertyInfo, Func`1 propertyConfiguration, ModelConfiguration modelConfiguration)
   bij System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapPrimitiveOrComplexOrEnumProperty(PropertyInfo propertyInfo, Func`1 structuralTypeConfiguration, Boolean discoverComplexTypes)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<>c__DisplayClassb.<MapComplexType>b__7(PropertyMapper m, PropertyInfo p)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapStructuralElements[TStructuralTypeConfiguration](Type type, ICollection`1 annotations, Action`2 propertyMappingAction, Func`1 structuralTypeConfiguration)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapComplexType(Type type, Boolean discoverNested)
   bij System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapPrimitiveOrComplexOrEnumProperty(PropertyInfo propertyInfo, Func`1 structuralTypeConfiguration, Boolean discoverComplexTypes)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<>c__DisplayClassb.<MapComplexType>b__7(PropertyMapper m, PropertyInfo p)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapStructuralElements[TStructuralTypeConfiguration](Type type, ICollection`1 annotations, Action`2 propertyMappingAction, Func`1 structuralTypeConfiguration)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapComplexType(Type type, Boolean discoverNested)
   bij System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapPrimitiveOrComplexOrEnumProperty(PropertyInfo propertyInfo, Func`1 structuralTypeConfiguration, Boolean discoverComplexTypes)
   bij System.Data.Entity.ModelConfiguration.Mappers.PropertyMapper.MapIfNotNavigationProperty(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.<>c__DisplayClass14.<MapEntityType>b__e(PropertyMapper m, PropertyInfo p)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapStructuralElements[TStructuralTypeConfiguration](Type type, ICollection`1 annotations, Action`2 propertyMappingAction, Func`1 structuralTypeConfiguration)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
   bij System.Data.Entity.ModelConfiguration.Mappers.NavigationPropertyMapper.Map(PropertyInfo propertyInfo, EntityType entityType, Func`1 entityTypeConfiguration)
   bij System.Data.Entity.ModelConfiguration.Mappers.TypeMapper.MapEntityType(Type type)
   bij System.Data.Entity.DbModelBuilder.MapTypes(EdmModel model)
   bij System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
   bij System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   bij System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   bij System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   bij System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   bij System.Data.Entity.Database.Initialize(Boolean force)
   bij Contacts.DAL.EF.EFRepository..ctor() in C:\VisualStudio\p1w1\Prak_Contacten\DAL\EF\EFRepository.cs:regel 17
   bij Contacts.BL.ContactManager..ctor() in C:\VisualStudio\p1w1\Prak_Contacten\BL\ContactManager.cs:regel 18
   bij UI.CA.Program.Main(String[] args) in C:\VisualStudio\p1w1\Prak_Contacten\UI.CA\Program.cs:regel 18
   bij System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   bij System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   bij Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   bij System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   bij System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   bij System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   bij System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   bij System.Threading.ThreadHelper.ThreadStart()
   InnerException: 

这是我的代码 上下文

namespace Contacts.DAL.EF
{

[DbConfigurationType(typeof(ContactsDbConfiguration))]
internal class ContactsDbContext : DbContext
{
    public ContactsDbContext() : base("ContactsDBEF")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<Contact>().Property(c => c.Name).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute()));
        modelBuilder.Entity<Contact>().HasKey(c => c.PersonId);
        modelBuilder.ComplexType<Address>();
        modelBuilder.ComplexType<Address>().Ignore(a => a.AddressId);
        modelBuilder.Entity<Category>().HasKey(c => c.CatergoryId);
     }


    public DbSet<Contact> Contacts { get; set; }
    public DbSet<Category> Categories { get; set; }
 }
}

配置

 namespace Contacts.DAL.EF
 {
 class ContactsDbConfiguration:DbConfiguration
 {
    public ContactsDbConfiguration()
    {

        this.SetDefaultConnectionFactory(new System.Data.Entity.Infrastructure.SqlConnectionFactory());
        this.SetProviderServices("System.Data.SqlClient", System.Data.Entity.SqlServer.SqlProviderServices.Instance);

        this.SetDatabaseInitializer<ContactsDbContext>(new ContactsDbInitializer());
    }
}
}

初​​始化程序

 namespace Contacts.DAL.EF
 {
  internal class ContactsDbInitializer:DropCreateDatabaseAlways<ContactsDbContext>
{
    protected override void Seed(ContactsDbContext context)
    {
        context.Categories.Add(new Category()
        {
            CatergoryId = 1,
            Description = "Family"
        });
        context.Categories.Add(new Category()
        {
            CatergoryId = 2,
            Description = "Friends"
        });
        context.Categories.Add(new Category()
        {
            CatergoryId = 3,
            Description = "School"
        });
        context.Categories.Add(new Category()
        {
            CatergoryId = 4,
            Description = "Sports"
        });
        context.SaveChanges();

        context.Contacts.Add(new Contact()
        {
            PersonId = 1,
            Name = "Verstraeten Micheline",
            Address = new Address()
            {
                StreetAndNumber = "Antwerpsestraat 20",
                Zipcode = 2000,
                City = "Antwerpen"
            },
            Gender = Gender.Female,
            Blocked = false,
            Birthday = new DateTime(1978, 8, 30),
            Phone = "03/123.45.67",
            Mobile = "0495/11.22.33",
            Categories = new List<Category>() { context.Categories.ToList()[0] }
        });
        context.Contacts.Add(new Contact()
        {
            PersonId = 2,
            Name = "Bogaerts Sven",
            Address = new Address()
            {
                StreetAndNumber = "Brusselsestraat 10",
                Zipcode = 1000,
                City = "Brussel"
            },
            Gender = Gender.Male,
            Blocked = false,
            Birthday = new DateTime(1975, 4, 12),
            Mobile = "0478/12.34.56",
            Categories = new List<Category>() { context.Categories.ToList()[0], context.Categories.ToList()[2], context.Categories.ToList()[3] }
        });
        context.Contacts.Add(new Contact()
        {
            PersonId = 3,
            Name = "Vlaeminchx Dieter",
            Address = new Address()
            {
                StreetAndNumber = "Gentsestraat 95",
                Zipcode = 9000,
                City = "Gent"
            },
            Gender = Gender.Male,
            Blocked = true,
            Birthday = new DateTime(1981, 12, 8),
            Mobile = "0479 / 98.76.54",
            Categories = new List<Category>() { context.Categories.ToList()[0], context.Categories.ToList()[3] }
        });
        context.SaveChanges();
    }

}
}

使用数据方法的存储库

namespace Contacts.DAL.EF
{
public class EFRepository : IRepository
{
    private ContactsDbContext ctx;

    public EFRepository()
    {
        ctx = new ContactsDbContext();
        ctx.Database.Initialize(false);
    }

    public void CreateContact(Contact contactToInsert)
    {
        ctx.Contacts.Add(contactToInsert);
        ctx.SaveChanges();
    }

    public void DeleteContact(int id)
    {
        IEnumerable<Contact> temp = ctx.Contacts.AsEnumerable();
        Contact tempc = null;
        foreach(Contact c in temp)
        {
            if (c.PersonId==id)
            {
                tempc = c;
            }
        }
        ctx.Contacts.Remove(tempc);
        ctx.SaveChanges();
    }

    public IEnumerable<Category> ReadAllCategories()
    {
        return ctx.Categories.AsEnumerable();
    }

    public IEnumerable<Contact> ReadAllContacts(int? categoryId = default(int?))
    {
        if (categoryId == null)
        {
            return ctx.Contacts.AsEnumerable();
        }
        else {
            IEnumerable<Contact> temp = new List<Contact>();
            foreach (Contact c in ctx.Contacts.AsEnumerable()){
                foreach (Category ca in c.Categories)
                {
                    if (ca.CatergoryId == categoryId)
                    {
                        temp.ToList().Add(c);
                    }
                }
            }
            return temp;
        }                     
    }

    public Contact ReadContact(int id)
    {
        Contact temp=new Contact();
        foreach(Contact c in ctx.Contacts.AsEnumerable())
        {
            if(c.PersonId == id)
            {
                temp = c;
            }              
        }
        return temp;
    }

    public void UpdateContact(Contact contactToUpdate, Contact c)
    {
        for(int i = 0; i < ctx.Contacts.Count(); i++)
        {
            if (ctx.Contacts.ElementAt(i).PersonId == contactToUpdate.PersonId)
            {
                Contact temp = ctx.Contacts.ElementAt(i);
                temp = c;
                ctx.SaveChanges();
            }
        }
    }
}
}

0 个答案:

没有答案