英文:
Edit one-to-one parent and child together
问题
I have following parent and child models
public class Director
{
public int ID { get; set; }
public Home? Home { get; set; }
}
public class Home
{
public int ID { get; set; }
public int DirectorID { get; set; }
public Director Director { get; set; } = null!;
public string Location { get; set; } = string.Empty;
}
Is there a good way to edit director and home together?
Currently, I always have the ModelState error that ErrorMessage [string]: "The Director field is required."
In the htmlcs, I use the following to update the home location inside director edit page.
<div class="form-group">
<label asp-for="Director.Home.Location" class="control-label"></label>
<input asp-for="Director.Home.Location" class="form-control" />
<span asp-validation-for="Director.Home.Location" class="text-danger"></span>
</div>
英文:
I have following parent and child models
public class Director
{
public int ID { get; set; }
public Home? Home { get; set; }
}
public class Home
{
public int ID { get; set; }
public int DirectorID { get; set; }
public Director Director { get; set; } = null!;
public string Location { get; set; } = string.Empty;
}
Is there a good way to edit director and home together?
Currently, I always have the ModelState error that ErrorMessage [string]:
"The Director field is required."
In the htmlcs, I use the following to update the home location inside director edit page.
<div class="form-group">
<label asp-for="Director.Home.Location" class="control-label"></label>
<input asp-for="Director.Home.Location" class="form-control" />
<span asp-validation-for="Director.Home.Location" class="text-danger"></span>
</div>
答案1
得分: 1
以下是翻译好的部分:
答案很简单 - 不要将您的实体用作模型(有多种原因,包括诸如过度发布攻击等),创建专门的类来实现此目标。例如:
public class DirectorUpdateModel
{
public int ID { get; set; }
public HomeUpdateModel Home { get; set; }
}
public class HomeUpdateModel
{
public int ID { get; set; }
public string Location { get; set; } = string.Empty;
}
将实体映射到视图模型,然后将它们映射回相应的实体。
英文:
The simple answer is - do not use your entities as models (there are multiple reasons for this, including things like overposting attacks), create special classes for this goal. For example:
public class DirectorUpdateModel
{
public int ID { get; set; }
public HomeUpdateModel Home { get; set; }
}
public class HomeUpdateModel
{
public int ID { get; set; }
public string Location { get; set; } = string.Empty;
}
Map entities to models for views and then map them back to corresponding entities.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论