传递 ObjectContext EF 4.0

发布于 2024-11-02 07:16:30 字数 1318 浏览 0 评论 0原文

我有两个类 Queries 和 ContactRepository。

    public static class Queries
    {
        public static Contact GetContactByName(CEntities context, string name)
        {
            return (from Contact c in context.Contacts
                    where c.Name == name
                    select c).FirstOrDefault();
        }
    }

    public class ContactRepository
    {
        private CEntities _dbContext;

        public ContactRepository()
        {
            _dbContext = new CEntities();
        }

        public void CreateContactAddress(string contactName, string address, string city, string state, string zip)
        {
            int contactId;
            ContactAddress ca = new ContactAddress();

            contactId = Queries.GetContactByName(_dbContext, contactName).Id;

            ca.ContactId = contactId;
            ca.Address = address
            ca.City = city;
            ca.State = state;
            ca.Zip = zip;

            _dbContext.ContactAddresses.AddObject(ca);
            _dbContext.SaveChanges();
        }
    }

当我调用 CreateContactAddress() 时,SaveChanges() 方法崩溃并出现以下错误:

无法确定有效的排序 对于相关操作。依赖关系 可能由于外键而存在 约束、模型要求或 存储生成的值。

我可以将 LINQ 查询移至 CreateContactAddress() 方法本身,一切都运行良好。谁能解释一下发生了什么事吗?

I have two classes Queries and ContactRepository.

    public static class Queries
    {
        public static Contact GetContactByName(CEntities context, string name)
        {
            return (from Contact c in context.Contacts
                    where c.Name == name
                    select c).FirstOrDefault();
        }
    }

    public class ContactRepository
    {
        private CEntities _dbContext;

        public ContactRepository()
        {
            _dbContext = new CEntities();
        }

        public void CreateContactAddress(string contactName, string address, string city, string state, string zip)
        {
            int contactId;
            ContactAddress ca = new ContactAddress();

            contactId = Queries.GetContactByName(_dbContext, contactName).Id;

            ca.ContactId = contactId;
            ca.Address = address
            ca.City = city;
            ca.State = state;
            ca.Zip = zip;

            _dbContext.ContactAddresses.AddObject(ca);
            _dbContext.SaveChanges();
        }
    }

When I call CreateContactAddress(), the SaveChanges() method crashes with the following error:

Unable to determine a valid ordering
for dependent operations. Dependencies
may exist due to foreign key
constraints, model requirements, or
store-generated values.

I can move the LINQ query into the CreateContactAddress() method itself, and everything works perfectly. Can anyone explain what is going on?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文