我遇到一些麻烦让一组实体设置正常工作。我在VS2012中使用EF v5对抗SQL Server 2008 R2 Express。
生成的数据库似乎一切正确,但我没有成功写入某些表。
我有一个UserProfile
对象定义如下:
[Table("UserProfile")]
public class UserProfile
{
[Key]
public long UserId { get; set; }
[StringLength(56)]
public string UserName { get; set; }
public Country Country { get; set; }
...
}
我还将Country
实体定义为:
[Table("Country")]
public class Country
{
[Key]
public int Id { get; set; }
[StringLength(2)]
public string CountryCode { get; set; }
[StringLength(100)]
public string CountryName { get; set; }
public ICollection<UserProfile> UserProfiles { get; set; }
...
}
生成的列在数据库中看起来是正确的,如果我把它编写成它看起来很好:
ALTER TABLE [dbo].[UserProfile] WITH CHECK ADD CONSTRAINT [UserProfile_Country] FOREIGN KEY([Country_Id])
REFERENCES [dbo].[Country] ([Id])
GO
仅用于控制器操作中的测试目的,我有以下内容:
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new
{
Country = new Country { Id = 223, CountryCode = "UK", CountryName = "UK" },
...
});
执行此WebSecurity
方法时,出现以下错误:
从对象类型MyApi.Data.Entities.Country到已知的托管提供程序本机类型不存在映射。
我尝试设置一个配置文件来指定代码和数据库中的关系,但它仍然不能正常播放。
配置如下:
public class CountryEntityConfig : EntityTypeConfiguration<Country>
{
public CountryEntityConfig()
{
this.HasMany(x => x.UserProfiles)
.WithRequired()
.HasForeignKey(FKey => FKey.Country);
}
}
在国家/地区对象中找到个人资料列表真的很奇怪我是否已经完全错误了?任何意见都赞赏。
修改
我已经修改了一些类,并在我现在拥有的用户配置文件中进行了一些更改:
public int CountryId { get; set; }
public virtual Country Country { get; set; }
Country.cs
public class Country
{
public int CountryId { get; set; }
[StringLength(2)]
public string CountryCode { get; set; }
[StringLength(100)]
public string CountryName { get; set; }
public virtual ICollection<UserProfile> UserProfiles { get; set; }
}
现在,数据库在UserProfile表中包含两个与CountryId相关的字段,并且与Country表有关系,我仍然收到原始错误消息。
TIA,
答案 0 :(得分:1)
No mapping错误可能是因为您没有将Country实体添加到DbContext。
在AccountModels.cs文件中,您将找到一个派生自DbContext的UsersContext,在那里您必须添加DbSet<Country>
。
但是,这里还有其他问题。例如,您正在使用Key创建Country表,默认情况下,EF将为Country表提供自动生成的标识列。这意味着您无法为ID插入值,它将自动生成。
国家/地区可能是一个查找表,无论如何您将填充国家/地区值。因此,您可能只需将CountryId设置为您想要的国家/地区的值