【发布时间】:2018-10-23 11:34:31
【问题描述】:
我正在使用 ASP .NET MVC5 和 EF6 构建一个 Web 应用程序。
我正在尝试将数据播种到这样定义的一对一关系:
模型
public class Client
{
public int ClientId { get; set; }
[Required]
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
[ForeignKey("Client")]
public int AddressId { get; set; }
[Required]
public string StreetName { get; set; }
public Client Client { get; set; }
}
地址是从属端。
现在,我想使用 EF 为这两个表添加种子,并在 /Migrations/Configuration.cs 中添加了以下代码:
internal sealed class Configuration : DbMigrationsConfiguration<MR_TrackTrace.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(MR_TrackTrace.Models.ApplicationDbContext context)
{
var clients = new List<Client>
{
new Client { Name = "John" },
new Client { Name = "Mary" },
new Client { Name = "Philip" }
};
clients.ForEach(s => context.Clients.AddOrUpdate(p => p.Name, s));
context.SaveChanges();
var addresses = new List<Address>
{
new Address { StreetName = "something", Client = clients.FirstOrDefault(s => s.Name == "John") },
new Address { StreetName = "other", Client = clients.FirstOrDefault(s => s.Name == "Philip") },
new Address { StreetName = "another", Client = clients.FirstOrDefault(s => s.Name == "Mary") }
};
addresses.ForEach(s => context.Addresses.AddOrUpdate(p => p.Name, s));
context.SaveChanges();
}
}
现在,在添加迁移和更新数据库之后,我检查了表,客户端是根据构建和播种的,但是地址表有一个名为 ClientId 的列,因为它是外键。
但是此列没有填充预期的 ID,而是填充了“0”。通过使用:
Client = clients.FirstOrDefault(s => s.Name == "John")
我希望上下文会自动为该表设置 ClientId。
谁能帮我指导我解决这个问题? 提前致谢!
【问题讨论】:
-
你试过用 [Key] 装饰你的 clientId 属性吗?
-
@federicoscamuzzi 你的意思是,在客户端模型中给ClientId添加[Key]注解?
-
是 public int ClientId { get;放; } 添加[键]
-
你在哪里告诉 ClientId 是你的主键?
-
@federicoscamuzzi 刚刚尝试了您的建议,但不幸的是,没有任何变化。
标签: c# asp.net asp.net-mvc entity-framework entity-framework-6