0

I'm using CodeFirst with MVC 3 and have these two classes:

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; }       
}

When adding a new person I want to reference a city to this person. Therefore i'm using a SelectList with all cities in my view. The CityId and the object is transferred correctly to the Post-method, but when saving the changes to the database I will have a new object in the city-table (with same name, but new Id). I suggest there's something wrong with the relations in my models. Maybe somebody can help me.

4

1 回答 1

0

如果您为Person模型提供显式CityId属性,则无需City从存储库中检索对象,只需将CityId值直接分配给Person对象并保存即可。对于非常简单的视图,您也不需要使用视图模型,您可以在操作方法中接收一个Person实例并且已经被分配,假设视图中的 html 字段具有相同的名称。POSTCityId

这应该可以解决您的问题,因为您将知道您正在明确使用已经存在的 CityId。

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

于 2013-01-03T12:34:53.347 回答