У меня есть две таблицы базы данных, одна из которых является родительской, а другая дочерней. Родительская таблица имеет ссылку на дочернюю таблицу. Таблица базы данных была сгенерирована с использованием подхода первого кода с моделями данных ниже:
[Table("Family")]
public partial class Family
{
public int Id { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public int RoleId { get; set; }
public int FuId { get; set; }
public int RiskAreaId { get; set; }
public int LocationId { get; set; }
public DateTime CreatedDate { get; set; }
[ForeignKey("RoleId")]
public virtual Role Role { get; set; }
[ForeignKey("FuId")]
public virtual FamilyUnit FamilyUnit { get; set; }
[ForeignKey("RiskAreaId")]
public virtual RiskArea RiskArea { get; set; }
[ForeignKey("LocationId")]
public virtual Location Location { get; set; }
}
И таблица FamilyUnit, я ниже:
[Table("FamilyUnit")]
public partial class FamilyUnit
{
public int Id { get; set; }
[Column(TypeName = "varchar")]
[StringLength(50)]
[Required]
public string FamilyUnitName { get; set; }
public virtual IEnumerable<Family> Families { get; set; }
}
Затем я создал проект webAPI, чтобы мой проект мог использовать API. Мой Api показан ниже:
[EnableCors("*", "*", "*")]
public class FamilyUnitController : ApiController
{
FamilyUnitBs familyUnitObjBs;
public FamilyUnitController()
{
familyUnitObjBs = new FamilyUnitBs();
}
[ResponseType(typeof(IEnumerable<FamilyUnit>))]
public IHttpActionResult Get()
{
var famUnits = familyUnitObjBs.GetALL();
return Ok(famUnits);
}
[ResponseType(typeof(FamilyUnit))]
public IHttpActionResult Get(int id)
{
FamilyUnit familyUnit = familyUnitObjBs.GetByID(id);
if (familyUnit != null)
return Ok(familyUnit);
else
return NotFound();
}
[ResponseType(typeof(FamilyUnit))]
public IHttpActionResult Delete(int id)
{
FamilyUnit familyUnit = familyUnitObjBs.GetByID(id);
if (familyUnit != null)
{
familyUnitObjBs.Delete(id);
return Ok(familyUnit);
}
else
{
return NotFound();
}
}
}
Затем я создал другой проект, который вызывал интерфейс приложения для использования методов API.
Ниже представлен контроллер angularjs с заводским обслуживанием
appEIS.factory('familyMgmtService', function ($http,$rootScope) {
famMgmtObj = {};
famMgmtObj.getAll = function () {
var Fams;
Fams = $http({ method: 'Get', url:$rootScope.ServiceUrl+ 'FamilyUnit' }).
then(function (response) {
return response.data;
});
return Fams;
};
famMgmtObj.createFamily = function (fam) {
var Fam;
Fam = $http({ method: 'Post', url:$rootScope.ServiceUrl+ 'Family', data: fam }).
then(function (response) {
return response.data;
}, function(error) {
return error.data;
});
return Fam;
};
famMgmtObj.deleteFamilyById = function (eid) {
var Fams;
Fams = $http({ method: 'Delete', url:$rootScope.ServiceUrl+ 'FamilyUnit', params: { id: eid } }).
then(function (response) {
return response.data;
});
return Fams;
};
famMgmtObj.getFamilyByFuId = function (fid) {
var Fams;
console.log(fid);
Fams = $http({ method: 'Get', url: $rootScope.ServiceUrl + 'Family', params: { id: fid } }).
then(function (response) {
return response.data;
});
return Fams;
};
return famMgmtObj;
});
appEIS.controller('familyMgmtController', function ($scope, familyMgmtService, utilityService, $window) {
$scope.Sort = function (col) {
$scope.key = col;
$scope.AscOrDesc = !$scope.AscOrDesc;
};
familyMgmtService.getAll().then(function (result) {
$scope.Fams = result;
console.log(result);
});
$scope.CreateFamily = function (Fam, IsValid) {
if (IsValid) {
$scope.Fam.Password = utilityService.randomPassword();
familyMgmtService.createFamily(Fam).then(function (result) {
if (result.ModelState == null) {
$scope.Msg = " You have successfully created " + result.FamilyId;
$scope.Flg = true;
utilityService.myAlert();
$scope.serverErrorMsgs = "";
familyMgmtService.getAll().then(function (result) {
$scope.Fams = result;
});
}
else {
$scope.serverErrorMsgs = result.ModelState;
}
});
}
};
$scope.DeleteFamilyById = function (Fam) {
if ($window.confirm("Do you want to delete Family with Id:" + Fam.FamilyId + "?")) {
familyMgmtService.deleteFamilyById(Fam.FamilyId).then(function (result) {
if (result.ModelState == null) {
$scope.Msg = " You have successfully deleted " + result.FamilyId;
$scope.Flg = true;
utilityService.myAlert();
familyMgmtService.getAll().then(function (result) {
$scope.Fams = result;
});
}
else {
$scope.serverErrorMsgs = result.ModelState;
}
});
}
};
$scope.GetFamilyByFuId = function (Fam) {
familyMgmtService.getFamilyByFuId(Fam.fid).then(function (result) {
console.log(result);
$scope.Fams = result;
});
};
$scope.CreateMultiFamily = function () {
var file = $scope.myFile;
var uploadUrl = "http://localhost:60736/api/Upload/";
utilityService.uploadFile(file, uploadUrl, $scope.eid).then(function (result) {
$scope.image = result;
});
};
});
Семейная единица хорошо отображается в списке аккордеонов, но различные семейства не отображаются с использованием идентификатора familyUnit, как показано ниже:
<div class="panel-body">
<div dir-paginate="emp in Fams | filter:search | orderBy:key:AscOrDesc | itemsPerPage:10" class="wrapper center-block">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="heading{{emp.Id}}">
<h4 class="panel-title">
<div role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse{{emp.Id}}" aria-expanded="true" aria-controls="collapse{{emp.Id}}">
{{emp.FamilyUnitName}}
</div>
</h4>
</div>
<div id="collapse{{emp.Id}}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading{{emp.Id}}">
<div class="panel-body">
<div ng-repeat="f in emp.Families">{{f.FirstName}} - {{f.Surname}}</div>
</div>
</div>
</div>
</div>
</div>