【发布时间】:2013-08-07 12:33:50
【问题描述】:
我正在尝试使用一对一映射将旧用户表拆分为两个实体,但不断收到迁移错误,指出我的数据库不同步,即使所有内容(我认为已映射)并且我正在尝试制作一对一的关系。
这是一个现有的数据库(尽管我首先使用代码,因为迁移将变得很重要)但我没有对数据库添加任何更改(尽管我不确定一对一的表拆分到底期望什么),我不断得到这个:
The model backing the 'Context' context has changed since the database was created. Consider using Code First Migrations to update the database
我可以更新数据库(手动或通过迁移),但不知道实际不同步的是什么,因为没有添加新字段并且名称匹配。
基础实体:
public abstract class BaseEntity<T>
{
[Key]
public T Id { get; set; }
public DateTime CreatedOn { get; set; }
}
会员模式:
public class Membership : BaseEntity<Guid>
{
public string UserName { get; set; }
public bool Approved { get; set; }
public bool Locked { get; set; }
public Profile Profile { get; set; }
}
个人资料模型:
public class Profile : BaseEntity<Guid>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Extension { get; set; }
public Membership Membership { get; set; }
}
成员映射(具有 1 对 1 定义):
public class MembershipMap : EntityTypeConfiguration<Membership>
{
public MembershipMap()
{
//Primary Key
this.HasKey(t => t.Id);
//**Relationship Mappings
this.HasRequired(m => m.Profile)
.WithRequiredPrincipal(p => p.Membership);
//Properties & Column mapping
this.Property(m => m.Id)
.HasColumnName("PKID")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(m => m.UserName)
.HasColumnName("Username")
.HasMaxLength(255);
this.Property(m => m.Approved)
.HasColumnName("IsApproved");
this.Property(m => m.Locked)
.HasColumnName("IsLocked");
this.Property(m => m.CreatedOn)
.HasColumnName("CreationDate");
this.ToTable("AppUser");
}
}
个人资料映射:
public class ProfileMap : EntityTypeConfiguration<Profile>
{
public ProfileMap()
{
//Primary Key
this.HasKey(t => t.Id);
//Properties & Column mapping
this.Property(m => m.Id)
.HasColumnName("PKID")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(m => m.FirstName)
.HasColumnName("FirstName");
this.Property(m => m.LastName)
.HasColumnName("LastName");
this.Property(m => m.Email)
.HasColumnName("Email");
this.Property(m => m.Telephone)
.HasColumnName("Telephone");
this.Property(m => m.Extension)
.HasColumnName("Extension");
this.ToTable("AppUser");
}
}
数据库表 我知道并非所有字段都已映射,但我现阶段不需要它们,这肯定不是问题吧?
【问题讨论】:
-
澄清一下,您是否已经在此模型上运行了迁移?
-
我目前没有使用任何迁移,数据库是预先存在的,并且类的模型应该与数据库的模型匹配。我现在正在检查整个事情,看看这是不是在其他地方。
-
尝试运行
update-database -script命令,查看迁移生成的更改脚本。这应该会给你一个关于它缺少什么的线索。 -
谢谢你,经过一番折腾后,我得到了脚本……它很庞大,但我想我可能知道发生了什么。当我开始这个时,我正在使用现有的数据库,但模型略有变化,所以我采用了保持不变的表并增强了新结构。关键是我更改了数据库并简化了命名约定,例如“项目”变成了“项目”我怎样才能重置迁移所以我基本上又开始了????
-
就我个人而言,我只是删除了已添加到项目中的 Migrations 文件夹。不过手头有点重!
标签: c# .net entity-framework entity-framework-5