CTP5 EF代码第一个问题

Kyl*_*ers 6 .net c# asp.net asp.net-mvc entity-framework

您可以在http://code.google.com/p/contactsctp5/找到演示此问题的源代码

我有三个模型对象.联系,的ContactInfo,ContactInfoType.如果联系人有许多contactinfo,并且每个contactinfo都是contactinfotype.我觉得相当简单.我遇到的问题是当我去编辑联系对象时.我从我的联系人存储库中取出它.然后我运行"UpdateModel(contact);" 并使用我的表单中的所有值更新对象.(使用debug进行监视)当我保存更改时,我收到以下错误:

操作失败:无法更改关系,因为一个或多个外键属性不可为空.当对关系进行更改时,相关的外键属性将设置为空值.如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象.

似乎在我调用更新模型后它将我的引用置空并且这似乎打破了一切?任何有关如何补救的想法将不胜感激.谢谢.

这是我的模特:

public partial class Contact {
    public Contact() {
      this.ContactInformation = new HashSet<ContactInformation>();
    }

    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<ContactInformation> ContactInformation { get; set; }
 }

 public partial class ContactInformation {
    public int ContactInformationId { get; set; }
    public int ContactId { get; set; }
    public int ContactInfoTypeId { get; set; }
    public string Information { get; set; }

    public virtual Contact Contact { get; set; }
    public virtual ContactInfoType ContactInfoType { get; set; }
  }

  public partial class ContactInfoType {
    public ContactInfoType() {
      this.ContactInformation = new HashSet<ContactInformation>();
    }

    public int ContactInfoTypeId { get; set; }
    public string Type { get; set; }

    public virtual ICollection<ContactInformation> ContactInformation { get; set; }
  }
Run Code Online (Sandbox Code Playgroud)

我的控制器动作:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Contact person) {
      if (this.ModelState.IsValid) {
        var contact = this.contactRepository.GetById(person.ContactId);
        UpdateModel(contact);
        this.contactRepository.Save();
        TempData["message"] = "Contact Saved.";
        return PartialView("Details", contact);
      } else {
        return PartialView(person);
      }
    }
Run Code Online (Sandbox Code Playgroud)

上下文代码:

protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
      modelBuilder.Entity<Contact>()
        .HasMany(c => c.ContactInformation)
        .WithRequired()
        .HasForeignKey(c => c.ContactId);

      modelBuilder.Entity<ContactInfoType>()
        .HasMany(c => c.ContactInformation)
        .WithRequired()
        .HasForeignKey(c => c.ContactInfoTypeId);
    }
Run Code Online (Sandbox Code Playgroud)

小智 1

感谢实体框架网站上的 Morteza Manavi,我解决了这个问题。我的问题是由我的 ContactInformation 模型属性“contactid”和“contacttypeid”不可为空引起的。一旦我修复了这个问题,UpdateModel() 的一切就可以正常工作了。非常感谢!