r/angularjs • • May 21 '16

HELP , AngularJS - Entity Framework app only shows ID's

Hello, I've been stuck in this problem for about 2 days,

I'm making an angular app that is using entity framework in the back end and angular in the front, the database created in visual studio 2015. I have 3 tables where my associative table has 2 foreign keys.

When I pull data from the main associative table I get the main values and the ID values of the other 2 tables. sorta like this. this is obvious because im telling it to do that.

Sections IdCodeNumberDateUserIdRankId
datadatadata16
datadatadata24
datadatadata

So my questions is , how can I replace those ID values with Angular , Like I said, they are foreign key values. so data instead of numbers.

Thank you in advance

my app.js

var myApp = angular.module('myApp', []);
myApp.controller('maincontroller', function ($scope, $http) {
$http.get('/home/GetSections')
.success(function (result) {
$scope.sections = result;
})
.error(function (data) {
    console.log(data);
});
});

my index.cshtml

<h2>Sections</h2>

<div ng-controller="maincontroller">
<table class="table">
    <tr>
        <th>Sections Id </th>
        <th>Code Number</th>
        <th>Date </th>
        <th>User Id </th>
        <th>Rank Id </th>
    </tr>
    <tr ng-repeat="section in sections">
        <td>{{section.SectionId}} </td>
        <td>{{section.CodeNumber}} </td>
        <td>{{section.Date.replace('/Date(','').replace(')/','') | date:"MM/dd/yyyy"}} </td>
        <td>{{section.UserId}}</td>
        <td>{{section.RankId}}</td>
    </tr>
</table>
</div>

My homecontroller.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FireLab.Controllers
{
public class HomeController : Controller
{
 // GET: Home
 public ActionResult Index()
{
        return View();
    }
    public JsonResult GetSections()
    {
        var db = new FireDBEntities();
        var sections = db.Sections.ToList();
        return Json(sections, JsonRequestBehavior.AllowGet);
    }
}
}

btw, I've tried different options like ng-options and filters , but they dont seem to work I get blank I if add them

0 Upvotes

24 comments sorted by

2

u/HDmac May 21 '16

This is an EF issue, if your pulling back the id's instead of the objects, your only going to get id's. You'll need to modify your c# code and or database database.

1

u/corganfuzz May 21 '16

Ahh...I just realized visual studio added a 1 to Rank , which probably was caused by a typo I made. Let me re-do the project and I'll post my findings

1

u/corganfuzz May 21 '16 edited May 21 '16

You guys are probably right. However, I have thought about a solution so let me run it by you.

First, as you can see in my c# controller there is a variable called sections , this variable is bind it and you can see it in my app.js This works, because if I go to /home/GetSections i get JSON. ( this is the JSON from my associative table tho)

Second, lets say I create 2 more variables in order to get JSON from the other 2 tables. I've tried that bind it with my app.js and this works. I get JSON from my other 2 tables

Now, here's when I think it becomes pure angular. Basically , It will just be a matter of put the new 2 variables I've created inside my HTML with the {{}} brackets thingies, but as you can see here in this line.

<tr ng-repeat="section in sections">

Im using ng-repeat. and the variable I've created it first. Therefore, I cannot use any more variables., so how do I included the other 2 variables that are giving me the JSON I want. should I use ng-options ?.

In general. What is the command/code you guys use when it comes to pull data that has foreign keys in angular? like most of the tutorials I'm using ONLY include pulling data from 1 table and never 3 connected tables. Here's the one I kinda use so you guys have a general idea of what I did

Here

Personally I think even if I get the C# modified in EF. I will still need a way to pull it from angular, and (samples in samples, it's not gonna cut it ) don't you guys think?

1

u/angularfox May 21 '16

Its up to your web api to return the correct Json structure that has those other tables data nested in the sections results. Then you should be able to access them in JavaScript like any other object with .dot notation {{section.User.UserId}}

1

u/corganfuzz May 21 '16

so if my user table is

Users
UserId (PK)
Fname
Lname

then if I want to pull Fname and Lname only , my angular code will be ?

<td> {{section.UserId.Fname.Lname}}</td>

and not:

<td> {{section.Users.Fname.Lname}}</td>

right ?..if this is correct maybe I can just leave it like that and start messing with the C# code , but I know one part is correct for sure

4

u/lintho May 21 '16

As far as i see it this has nothing to do with angular? You want to retrieve a different data from the database, and that is before you get the data to frontend. Am i missing something?

1

u/SarSha May 21 '16

Include the nested tables when fetching the data:

var sections = db.Sections.Include("User").Include("Rank").ToList();

That will tell EF to pull the related data as well.

1

u/corganfuzz May 21 '16

humm... I've implemented this and I get

A circular reference was detected while serializing an object of type 'FireBD.Section

I thought I got rid of this error at the beginning disabling the proxy. crap now it gets more confusing

1

u/SarSha May 22 '16

That is because you send the Section object as is, the Section obj now contain a User obj which contain the Section obj reference, this causing the circular error.

You need to map it to something like a SectionViewModel object that will be sent to the client.

1

u/corganfuzz May 22 '16

How do i do that? ...sorry im new at .net, like should I create a SectionViewModel.cs class inside the models folder , and then what ? what do I write there ?

1

u/SarSha May 22 '16
var sectionVM = new SectionVM();
sectionVM.UserVM = new UserVM();

and now you populate the properties from your original Section object:

sectionVM.UserVM.Name = section.User.Name;
sectionVM.UserVM.Fname = section.User.Fname;
....
sectionVM.Date = section.Date;
sectionVM.Id = section.Id

You basically just copying the properties from your Section object to the SectionVM object.

And then you send the SectionVM back to the client.

1

u/ineed2ineed2 May 21 '16

Have you tried setting a break point at your .success function in your app.js. My gut feeling is that the JSON being passed back from your homecontroller.cs is not the same structure as you think. I could be wrong but I think .net puts associated table data in a list, so in JSON you may have to look at a nested object.

If you are not getting all the data you expect back from your controller.cs then this is a .net problem.

0

u/corganfuzz May 21 '16

The more I see this, the more I'm convinced this is EF problem. so you guys are right. It probably has to do with the models auto generated by visual studio 2015. yo gotta love VS ( or BS for that matter). I'll try another approach

1

u/soulblow May 23 '16

This isn't an EF problem. It's that you don't understand any of the parts you're using.

You have 3 parts that you're working with.

  1. The data layer (EF)

  2. Web API

  3. Angular

The program is doing exactly what you're telling it to, but the problem is that you don't know how to tell it.

You can edit the models to do what you want (within reason). Can you post your models and their mappings?

1

u/corganfuzz May 23 '16 edited May 23 '16

Ok so I've followed your advice and re-did the whole thing with the Web API template on VS

These are my steps:

  1. New Project > Web API

  2. Added a SQL database, create tables and inserted data on them

  3. Right click controllers folder and selected "Web API 2 Controller with actions using EF"

  4. Edited the index.html and put the code I've displayed above in my question starts with <h2> sections </h2>

  5. Since this is WEb API I've changed the angular code to the following:

my App.js

var myApp = angular.module('myApp', []);
myApp.controller('maincontroller', function ($scope, sectionService) {

getsections();

function getsections() {
    sectionService.getsections()
        .success(function (sections) {
            $scope.sections = sections;
        });
                
}
});

my service.js

myApp.factory('sectionService', ['$http', function ($http) {

var urlBase = 'http://localhost:35656/api';
var sectionService = {};
sectionService.getsections = function () {
    return $http.get(urlBase + '/sections');
};

return sectionService;

}]);

here are my tables: ( created in VS)

RankSectionUser
RankId (PK)SectionId (PK)UserId (PK)
RankNameCodeNumberFName
DateLName
UserId (FK)
RankID (FK)

my index.cshtml

<h2>Sections</h2>

<div ng-controller="maincontroller">
<table class="table">
<tr>
    <th>Sections Id </th>
    <th>Code Number</th>
    <th>Date </th>
    <th>User Id </th>
    <th>Rank Id </th>
</tr>
<tr ng-repeat="section in sections">
    <td>{{section.SectionId}} </td>
    <td>{{section.CodeNumber}} </td>
    <td>{{section.Date.replace('/Date(','').replace(')/','') | date:"MM/dd/yyyy"}} </td>
    <td>{{section.UserId}}</td>
    <td>{{section.RankId}}</td>
</tr>
</table>
</div>

Everything else is default from the WeBAPI template from Visual Studio.

so my Models are generated by EF:

User.cs

namespace KLab.Models
{
using System;
using System.Collections.Generic;

public partial class User
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public User()
    {
        this.Sections = new HashSet<Section>();
    }

    public int UserId { get; set; }
    public string Fname { get; set; }
    public string Lname { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Section> Sections { get; set; }
}
}

my Rank.cs

namespace KLab.Models
{
using System;
using System.Collections.Generic;

public partial class Rank
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Rank()
    {
        this.Sections = new HashSet<Section>();
    }

    public int RankId { get; set; }
    public string RankName { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Section> Sections { get; set; }
}
}

My Section.cs

namespace KLab.Models

{ using System; using System.Collections.Generic;

public partial class Section
{
    public int SectionId { get; set; }
    public Nullable<int> CodeNumber { get; set; }
    public Nullable<System.DateTime> CreatedAt { get; set; }
    public int UserId{ get; set; }
    public int RankId { get; set; }
    public virtual Rank Rank { get; set; }
    public virtual User User { get; set; }
}

}

My KlabModel.Context.cs

namespace KLab.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

public partial class KLabDBEntities : DbContext
{
    public KLabDBEntities()
        : base("name=KLabDBEntities")
    {
        Configuration.ProxyCreationEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Section> Sections { get; set; }
    public virtual DbSet<Rank> Rank { get; set; }
    public virtual DbSet<User> Users { get; set; }
}
}

I also have a KlabModel.cs but is empty

When I build i get:

Sections IdCodeNumberDateUserIdRankId
datadatadata16
datadatadata24
datadatadata

My goal is to change those id numbers to the actual data of the tables , they are foreign key values

Ohh yeah I forgot, so obviously is pulling IDs because Im telling it to do so, in this line:

<td>{{section.RankId}}</td>

SO I've changed it to this one:

<td>{{section.RankId.RankName}}</td> 

I get no values in that column

1

u/soulblow May 23 '16

The shortest answer is to remove the lazy loading from the section model (My section.cs)

Change

public virtual Rank Rank { get; set; }
public virtual User User { get; set; }

to

public Rank Rank { get; set; }
public User User { get; set; }

By default EF will set everything to lazy loading (which is much more efficient, and less dangerous). This is to avoid making complex queries to pull down information that you may or may not use. Lazy loading is preferred, because the information is requested the first time it's used. However, since you're serializing the data to JSON, the property is never explicitly accessed and therefore doesn't load the data.

That being said, I would strongly recommend not doing what I just told you and sticking to the restful api. By doing this, you're going against the architecture.

Instead, you should create api endpoints for all the objects and access them separately.

1

u/corganfuzz May 23 '16

Looks like the shortest answer didnt work.

I've added this on the KLabModel.Context.cs (db context)

Configuration.LazyLoadingEnabled = false;

and replace the value on index.cshtml

<td>{{section.RankId.RankName}}</td> 

no luck...sigh... i hate .net

1

u/soulblow May 23 '16

section.RankId.RankName

I'm not sure why you think this would exist, you edited the Rank property, not the RankId property.

What's the JSON response you're getting after removing virtual?

1

u/corganfuzz May 23 '16
[{"SectionId":1,"CodeNumber":129076,"Date":"2015-01-02T00:00:00","UserId":6,"RankId":3,"Rank":null,"User":null},
{"SectionId":2,"CodeNumber":850314,"Date":"2015-06-15T00:00:00","UserId":7,"RankId":3,"Rank":null,"User":null},
{"SectionId":3,"CodeNumber":176033,"Date":"2015-07-31T00:00:00","UserId":7,"RankId":0,"Rank":null,"User":null},
{"SectionId":4,"CodeNumber":129629,"Date":"2015-01-21T00:00:00","UserId":3,"RankId":0,"Rank":null,"User":null},"

hum...thats odd , rank and user are null

Also, chrome gives me the XML value like this , i guess thats normal?

<ArrayOfSection xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/KLab.Models">
  <Section>
      <CodeNumber>129076</CodeNumber>
      <Date>2015-01-02T00:00:00</Date>
      <SectionId>1</SectionId>
      <Rank i:nil="true"/>
      <RankId>3</RankId>
      <User i:nil="true"/>
      <UserId>6</UserId>
      </Section>
  <Section>
     <CodeNumber>850314</CodeNumber>
     <Date>2015-06-15T00:00:00</Date>
     <SectionId>2</SectionId>
     <Rank i:nil="true"/>
     <RankId>3</RankId>
     <User i:nil="true"/>
     <UserId>7</UserId>
  </Section>
  <Section>
    <CodeNumber>176033</CodeNumber>
    <Date>2015-07-31T00:00:00</Date>
    <SectionId>3</SectionId>
    <Rank i:nil="true"/>
    <RankId>0</RankId>
    <User i:nil="true"/>
    <UserId>7</UserId>
  </Section>
  <Section>
    <CodeNumber>129629</CodeNumber>
    <Date>2015-01-21T00:00:00</Date>
    <SectionId>4</SectionId>
    <Rank i:nil="true"/>
    <RankId>0</RankId>
    <User i:nil="true"/>
    <UserId>3</UserId>
  </Section>

1

u/soulblow May 23 '16

That is odd. Have you tried just accessing the entities directly, for testing purposes?

Just creating an instance of the dbcontext, and pulling the data into a collection or object? And seeing what the data looks like there?

1

u/corganfuzz May 23 '16

how do I do that?, sorry im new at .net

so if I I try to pull the JSON from users i get

  [{"RankId":1,"Condition":"Received","Sections":[]},{"RankId":2,"Condition":"Accessioning","Sections":[]},
  {"RankId":3,"Condition":"In Lab","Sections":[]},{"RankId":4,"Condition":"Report Generation","Sections":[]}]

this is if I go to /api/users in the browser

1

u/soulblow May 23 '16

You'll probably get a better explanation from the internet, compared to what I could provide. What you'll want to use is linq to entities. Google that and you should find a world of information.

This is how you can access the information in the code and not rely on web API.

It's very odd that the collections aren't populating. Without looking at the db schema, I really can't give much advice. Other than to try and use linq to entities to see what results you get manually vs serialization through web API.

0

u/[deleted] May 24 '16

[deleted]

1

u/soulblow May 24 '16

There's really no right answer. Something like this where you're pulling list and listitem is probably okay. Especially since they're directly related.

What I mean, is that listitem probably only exists to be part of a list.

Unlike something like section, user, and rank. Where they are all separate objects that can be related.

The other question is, how do you want these fields to be updated?

Are you going to only let listitems be updated along with a list, or will there be separate end points for listitem CRUD operations?

Ultimately, it all falls on your needs, how you'll use and manage the data, and if you plan to scale.

0

u/[deleted] May 24 '16

[deleted]

1

u/soulblow May 24 '16

Nah, you're just being thorough. I think for what you need, your approach will be fine.