gpt4 book ai didi

entity-framework-4.1 - Entity Framework 代码第一次违反一对一约束

转载 作者:行者123 更新时间:2023-12-02 02:20:35 24 4
gpt4 key购买 nike

给定以下简化模型:

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 集合时立即收到以下错误:

Multiplicity constraint violated. The role 'Account_ContactCard_Source' of the relationship 'InvestAdmin.Might.DataAccess.Account_ContactCard' has multiplicity 1 or 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 中定义一对一关系的内容,并尝试了许多不同的配置。所有人最终都会遇到同样的问题。

最佳答案

我发现我可以通过将关联的 ContactCard 的创建从 Account 构造函数移动到在 DBInitializer 的 Seed 方法中实际创建 Account 对象来解决这个问题。所以看起来这不是(直接)一对一关系的问题。

关于entity-framework-4.1 - Entity Framework 代码第一次违反一对一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8391100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com