2017-08-02 64 views
0

請問我是C#和實體框架的新手,我正在使用web api開發一個項目。我也使用郵遞員來測試我的數據並在插入數據庫之前驗證它們。 我的控制器創建將接受下面顯示的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" 
    } 
], 

回答

0

您的PersonModel的外觀如何?看看下面的代碼是否有幫助。

創建資產模型

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

,然後在PersonModel

public class PersonModel 
{ 

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

} 
+0

下面是我PersonModel代碼。請注意,我已刪除了部分性能,因爲該類太長 命名空間nsr.Domain.Model { 公共類PersonModel { 公衆詮釋標識{獲得;組; } public string FirstName {get;組; } public string MiddleName {get;組; public int MaritalStatusId {get;組; } public bool IsActive {get;組; } public virtual ICollection Assets {get;組; } public virtual ICollection SocialGroups {get;組; } } – codeDev

+0

@codeDev上面的示例是否適合您? –