【问题标题】:Saving data in many to many relationship using Entity Framework使用实体框架以多对多关系保存数据
【发布时间】:2017-08-02 18:23:03
【问题描述】:

请我是 C# 和实体框架的新手,我正在使用 web api 进行项目。我还使用邮递员来测试我的数据并在插入数据库之前对其进行验证。 我的控制器 Create 将接受如下所示的 json。 JSON 对象映射到我的人员模型,json 的 Assets 元素是资产模型的集合。我想要做的是检索 json 中的所有资产名称并检查它们是否存在于资产表中。如果它们存在,则获取资产的 ID 并将它们全部保存到“PersonAsset”表中。 请注意,“PersonAsset”包含“PersonID”和“AssetId”

我已经花了超过 24 小时试图解决这个问题,我需要帮助

    {
  "Id": 0,
  "FirstName": "stringFine",
  "MiddleName": "test-Sesan",
  "LastName": "stringOkay",
  "Gender": "Male",
  "DateOfBirth": "10-10-2017",
  "BirthCertificate": 0,
  "Asset": 0,
  "WorkTypeId": 2,
  "DwellingId": 2,
  "HouseholdRoleId": 2,
  "HealthFacility": 1,
  "Relationship": "string",
  "Education": 0,
  "MaritalStatusId": 2,
  "MobileNumber": "080099813501",
  "SettlementTypeId": 2,
  "CommunityId": 3,
  "SocialGroup": 0,
  "Address": "string",
  "IsInSchool": 0,
  "ReferenceNumber": "100/NSIO/NSR/345660",
  "DateInterviewed": "10-10-2017",
  "IsActive": true,
  "Assets": [
    {
      "Name": "Testing"
    }
  ],
  "SocialGroups": [
    {
      "Name": "string"
    }
  ]
}

   [ResponseType(typeof(PersonModel))]
    [ModelValidator]
    [HttpPost]
    public IHttpActionResult Create(PersonModel model)
    {

     try
        {
var person = Factory.Persons.Create(model);
 Service.Persons.Insert(person);
person = Service.Persons.Get(person.Id);
   var dto = Factory.Persons.Create(person);
  return CreatedAtRoute("DefaultApi", new { id = dto.Id },dto);
}
catch(dbexception){}

我如何接受以下 JSON 中的值并在我的控制器端点中使用它

"Assets": [
    {
      "Name": "Testing"
    }
 ],

【问题讨论】:

    标签: c# frameworks entity


    【解决方案1】:

    您的 PersonModel 是什么样的?看看下面的代码是否有帮助。

    创建资产模型

    public class Asset
    {
        public string Name { get; set; }
    }
    

    然后在 PersonModel 中

    public class PersonModel
    {
    
        public List<Asset> Assets { get; set; }
    
    }
    

    【讨论】:

    • 下面是我的 PersonModel 代码。请注意,我删除了一些属性,因为该类太长 namespace nsr.Domain.Model { public class PersonModel { public int Id { get;放; } 公共字符串名字 { 获取;放; } 公共字符串 MiddleName { 获取;放;公共 int MaritalStatusId { 获取;放; } 公共布尔 IsActive { 获取;放; } 公共虚拟 ICollectionAssets { 获取;放; } 公共虚拟 ICollection SocialGroups { 获取;放; } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2017-05-17
    • 2011-07-20
    • 2017-01-28
    相关资源
    最近更新 更多