Asp.net mvc MVC CodeFirst一对多关系创建新数据

Asp.net mvc MVC CodeFirst一对多关系创建新数据,asp.net-mvc,code-first,Asp.net Mvc,Code First,我将CodeFirst与MVC 3结合使用,并有以下两个类: public class Person { public int PersonId { get; set; } [Email] [Required] public string Email { get; set; } public string Passwort { get; set; } public virtual City City { get; set; } } publ

我将CodeFirst与MVC 3结合使用,并有以下两个类:

public class Person
{
    public int PersonId { get; set; }

    [Email]
    [Required]
    public string Email { get; set; }

    public string Passwort { get; set; }

    public virtual City City { get; set; }
}

public class City
{
    public int CityId { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual IEnumerable<Person> Persons { get; set; }       
}
公共类人物
{
公共int PersonId{get;set;}
[电邮]
[必需]
公共字符串电子邮件{get;set;}
公共字符串Passwort{get;set;}
公共虚拟城市城市{get;set;}
}
公营城市
{
public int CityId{get;set;}
[必需]
公共字符串名称{get;set;}
公共虚拟IEnumerable Persons{get;set;}
}
当添加一个新的人时,我想将一个城市引用给这个人。因此,我在视图中使用了一个包含所有城市的选择列表。CityId和对象被正确地传输到Post方法,但是在将更改保存到数据库时,city表中会有一个新对象(具有相同的名称,但具有新的Id)。
我认为我的模型中的关系有问题。也许有人能帮我。

如果你给你的
Person
模型一个显式的
CityId
属性,那么你就不需要从你的存储库中检索
City
对象,你只需将
CityId
值直接分配给
Person
对象并保存它。对于真正直观的视图,您也不需要使用viewmodel,您可以在
POST
操作方法中接收一个
Person
实例,并且假设视图中的html字段具有相同的名称,则已经分配了
CityId

这应该可以解决您的问题,因为这样您就会知道您正在显式使用一个已经存在的CityId


您的数据库将已经包含一个
Person.City\u CityId
字段,因此您不会创建任何新的内容,只会让自己更好地控制情况。有时您可能需要在模型中使用
[ForeignKey]
属性来连接
Person.CityId
属性与虚拟属性,但是使用标准命名约定应该没有必要。

保存时如何设置
City
属性?@MattiVirkkunen在我的映射方法中:
City=Repository.RepositoryManager.Instance.CityRepository.FindWithId(personViewModel.CitySelected.Value)
我正在数据库中搜索相应的对象…您是否尝试使用
[Identity]
属性装饰CityId属性?谢谢,效果很好!我不得不使用ForeignKey属性,但现在看起来很好:)