0

So I looked around but can't seem to find quite what I'm looking for.

I want to fetch a list of all my users in the database. I know that I can create a new User object, but I want the object to be created from the database, and return in a JSON format. I'm using entityframework.

    TimeFlowDbContext db = new TimeFlowDbContext();

    private List<User> _users = new List<User>
    {
        new User { 
            UserId = 1, 
            Firstname = "Test", 
            Lastname = "Man", 
            Username = "test", 
            Password = "test"
        }
    };

I've tried a lot of different things, but I don't really understand how to list them from my database and return JSON..

Thanks in advance if anyone can link me some documentations or explain the right answer.

2 Answers 2

1

Something like this should do the trick (using newtonsoft)

var users = db.users.select(a => new { a.UserId, a.Firstname, a.Lastname, a.Username });
var json = JsonConvert.SerializeObject(users);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Newtonsoft.JSON library for this. You can get this from Global Nuget Store.

Code to covert your entity farmework object as JSON.

    var settings = new JsonSerializerSettings()
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        Error = (sender, args) =>
        {
            args.ErrorContext.Handled = true;
        },
    };

    using(var db = new TimeFlowDbContext();)
    {
        var user = db.Users.First();
        return JsonConvert.SerializeObject(user, settings);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.