鉴于以下简化模型:
public class Account
{
public Account()
{
Id = Guid.NewGuid();
ContactCard = new ContactCard();
}
//[ForeignKey("ContactCard")]
public Guid Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public ContactCard ContactCard { get; set; }
}
public class ContactCard
{
public ContactCard()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public Account Account { get; set; }
}
public class MightDbContext: DbContext
{
public DbSet<Account> Accounts { get; set; }
public DbSet<ContactCard> ContactCards { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Account>().HasRequired(x => x.ContactCard).WithOptional(x => x.Account);
}
}
public class MightDbInitializer : DropCreateDatabaseIfModelChanges<MightDbContext>
{
protected override void Seed(MightDbContext context)
{
var accounts = new List<Account>
{
new Account()
{
Name = "Acme Corporation Pty. Ltd.",
Number = "001ABC"
},
new Account()
{
Name = "Three Little Pigs Pty. Ltd.",
Number = "002DEF"
}
};
accounts.ForEach(c => context.Accounts.Add(c));
}
}
以下简单的控制台程序来迭代Accounts和ContactCards集合的内容:
static void Main(string[] args)
{
Database.SetInitializer<MightDbContext>(new MightDbInitializer());
using (var context = new MightDbContext())
{
foreach (Account c in context.Accounts)
{
Console.WriteLine(c.ContactCard.Id);
}
var contactCards = context.ContactCards.ToList(); /* ERROR OCCURS HERE */
foreach (ContactCard a in contactCards)
{
Console.WriteLine(a.Id);
}
}
Console.Read();
}
为什么我在尝试访问ContactCards集合时会立即收到以下错误:
违反了多重性约束。 “InvestAdmin.Might.DataAccess.Account_ContactCard”关系的“Account_ContactCard_Source”角色具有多重性1或0..1。
当我查看实际存储在数据库表中的数据时,似乎都是正确的。实际上这是数据:
Accounts:
Id Name Number
ab711bad-1b32-42ca-b68b-12f7be831bd8 Acme Corporation Pty. Ltd. 001ABC
dc20a1dd-0ed4-461d-bc9c-04a85b555740 Three Little Pigs Pty. Ltd. 002DEF
ContactCards:
Id
dc20a1dd-0ed4-461d-bc9c-04a85b555740
ab711bad-1b32-42ca-b68b-12f7be831bd8
为了完整起见,这里是数据库中定义的Account_ContactCard外键约束:
-- Script Date: 06/12/2011 7:00 AM - Generated by ExportSqlCe version 3.5.1.7
ALTER TABLE [Accounts] ADD CONSTRAINT [Account_ContactCard] FOREIGN KEY ([Id]) REFERENCES [ContactCards]([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;
我一直在阅读Code First中定义一对一关系的所有内容,并尝试了许多不同的配置。所有人都回到了同样的问题。
答案 0 :(得分:2)
我发现我可以通过将关联的ContactCard从Account构造函数创建到DBInitializer的Seed方法中实际创建Account对象来解决此问题。所以看起来它并非(直接)是一对一关系的问题。