Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello

I have 2 tables named "User" and "Letter". each User can have many letters, so the relationship is "one to many". I want when a User login, see all letters that he/she have received in the jqxGrid. So I need Json format for my resources data to fill jqxGrid. I have wrote the codes below, but it shows Firs letter for each User due to "FirstorDefult". so
1)How can I return multi records ?
2) How can I convert Them to Json format?

Thanks in Advance

What I have tried:

in .js file :
JavaScript
var source =
    {
        // fetching data to grid
        datatype: "json",
        datafields: [
                    { name: 'UserName', type: 'string' },
                    { name: 'Text', type: 'string' }
        ],
        localdata: response,
    };

    // Data Adapter for Generating data for Grid
    var dataAdapter = new $.jqx.dataAdapter(source, {
        downloadComplete: function (data, status, xhr) { },
        loadComplete: function (data) { },
        loadError: function (xhr, status, error) { }
    });



in Controller :

C#
public string ShowUser()
        {
            using (Test02Entities _Test02Entities = new Test02Entities())
            {
                Join _Join = new Join();
                Letter _Letter = new Letter();
                Users _Users = _Test02Entities.Users.Where(c => c.ID==6).SingleOrDefault();
                if (_Users != null)
                {
                     _Letter = _Test02Entities.Letter.Where(c => c.UserID == _Users.ID).FirstOrDefault();
                    _Join.Text = _Letter.Text;
                    _Join.UserName = _Users.UserName;
                }
                return JsonConvert.SerializeObject(_Join);
            }
        }

        public partial class Join
        {
            public string UserName { get; set; }
            public string Text { get; set; }
        }
Posted
Updated 21-Oct-16 2:04am
Comments
Ehsan Sajjad 21-Oct-16 2:20am    
is it asp.net mvc?
Ali Majed HA 21-Oct-16 2:46am    
it is web api
F-ES Sitecore 21-Oct-16 8:40am    
Get a book on EF and go through it, or at least look at on-line tutorials. Linking entities is quite a basic aspect of EF and it is extremely wel documented.

1 solution

How this will work depends entirely on your Entity Framework approach.

If this is your database, and you're using Code First, the very best thing that you can do is define Navigation properties on your model classses. For instance:

C#
public class Users
{
   ... 
   public virtual ICollection<Letter> Letters { get; set;}
}

public class Letter
{
   ...
   [ForeignKey("User")]
   public int UserId { get; set; }

   [JsonIgnore]
   public virtual Users User { get; set; }
}

public string ShowUser(int id)
{
   using (Test02Entities _Test02Entities = new Test02Entities())
   {
      var user = _Test02Entities.Users.Find(id);
                
      return JsonConvert.SerializeObject(_Join);
   }
}

The JsonIgnore attribute will avoid the circular reference serialization issue. You can change this based on need, but that's outside the scope of a quick answer.

This pattern leverages the natural relational nature of data in a relational database to provide automatic joins, and is really one of the best ways to use Entity Framework (IMO).

As a side note, avoid using SingleOrDefault() if at all possible in EF as that will enumerate the entire table. FirstOrDefault() will stop enumeration when the condition is met, and Find() will pull directly by row key.

There is a primer for Navigation properties at:
Entity Framework Relationships & Navigation Properties[^].

If you're using Database First, you can do exactly the same thing by adding Associations to the edmx file. This approach is not as firmly in my realm, but there is a solid reference at:
Entity Framework Relationships - EF Designer[^]
 
Share this answer
 
v2
Comments
Dave Kreskowiak 21-Oct-16 13:14pm    
Your statements about SingleOrDefault and FirstOrDefault are not entirely true. They both get translated to SQL queries that limit the returned dataset from the database.

In the case of a SingleOrDefault query, that looks like this:
SELECT TOP (2) 
    [Extent1].columnName,
    ....
    FROM  [dbo].[someTable] AS [Extent1]
    WHERE expression

It's only slightly different for a FirstOrDefault:
SELECT TOP (1)
    [Extent1].columnName,
    ....
    FROM  [dbo].[someTable] AS [Extent1]
    WHERE expression
Nathan Minier 21-Oct-16 13:34pm    
I can accept that I was a little general with that.

In the case being discussed, though, the query will enumerate the whole table, as the target is a PK, as it would be for any unique index.
Dave Kreskowiak 21-Oct-16 13:39pm    
My example is a PK search, from a query like this:
using (var context = new DadContext())
{
    var result = context.Testtable.FirstOrDefault(tt => tt.Id == 9013);

    if (result == null)
    {
        ....
    }
}

It doesn't result in a full table scan.
Nathan Minier 21-Oct-16 13:51pm    
That would be because you're using FirstOrDefault. (TOP(1))

If you use SingleOrDefault (TOP(2)), the database will look for a second value, which it won't find due to the unique constraint on a PK, and will therefore search the whole table.
Dave Kreskowiak 21-Oct-16 14:04pm    
PK's are indexed automatically, so no it doesn't result in a full table scan.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900