简体   繁体   中英

Empty client-side models

I'm working on a Windows Phone 8.1 app, and I'm having trouble getting the client's model objects to obtain their values from the database that I'm hosting on Azure. The code I've written seems to work (at least iterate correctly), but my problem is that the Bars objects are empty. I don't know how to get them to obtain the values that are stored in the db (barID, barName, etc). I've built a working services project that I've published to an Azure website. This project contains my DTOs, context, and controllers. My client project contains models and views. Do I need to change my architecture? If so, how should I change it? Here's the code that's being called in my controller:

public class BarsController : ApiController
{
    private GatoradeShowerDB db = new GatoradeShowerDB();

    // GET: api/Bars
   // [Route("http://gatoradeshower.azurewebsites.net/api/bars/All")]
    public IQueryable<Bar> GetBars()
    {
        return db.Bars;
    }

    // GET: api/Bars/5
    [ResponseType(typeof(Bar))]
    public async Task<IHttpActionResult> GetBar(int id)
    {
        Bar bar = await db.Bars.FindAsync(id);
        if (bar == null)
        {
            return NotFound();
        }

        // return Ok(bar);
        return Ok(bar);
    }

    // PUT: api/Bars/5
    [ResponseType(typeof(void))]
    public async Task<IHttpActionResult> PutBar(int id, Bar bar)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != bar.BarID)
        {
            return BadRequest();
        }

        db.Entry(bar).State = EntityState.Modified;

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!BarExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

    // POST: api/Bars
    [ResponseType(typeof(Bar))]
    public async Task<IHttpActionResult> PostBar(Bar bar)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Bars.Add(bar);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = bar.BarID }, bar);
    }

    // DELETE: api/Bars/5
    [ResponseType(typeof(Bar))]
    public async Task<IHttpActionResult> DeleteBar(int id)
    {
        Bar bar = await db.Bars.FindAsync(id);
        if (bar == null)
        {
            return NotFound();
        }

        db.Bars.Remove(bar);
        await db.SaveChangesAsync();

        return Ok(bar);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool BarExists(int id)
    {
        return db.Bars.Count(e => e.BarID == id) > 0;
    }
}

Here's my DTO code:

public partial class Bar
{
    public int BarID { get; set; }

    [Required]
    [StringLength(255)]
    public string BarName { get; set; }

    [Required]
    [StringLength(255)]
    public string BarStreet { get; set; }

    [Required]
    [StringLength(50)]
    public string BarCity { get; set; }

    [Required]
    [StringLength(50)]
    public string BarState { get; set; }

    [Required]
    [StringLength(50)]
    public string BarPhone { get; set; }

    [Required]
    [StringLength(50)]
    public string BarZip { get; set; }
}

Here's my Context code:

public partial class GatoradeShowerDB : DbContext
{
    public GatoradeShowerDB()
        : base("name=GatoradeShowerDB")
    {
    }

    public virtual DbSet<Bar> Bars { get; set; }
    public virtual DbSet<Event> Events { get; set; }
    public virtual DbSet<Game> Games { get; set; }
    public virtual DbSet<Group> Groups { get; set; }
    public virtual DbSet<Member> Members { get; set; }
    public virtual DbSet<Stadium> Stadia { get; set; }
    public virtual DbSet<Team> Teams { get; set; }
    public virtual DbSet<TeamsTest> TeamsTests { get; set; }
    public virtual DbSet<WatchParty> WatchParties { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Game>()
            .Property(e => e.GameTime)
            .IsFixedLength();

        modelBuilder.Entity<TeamsTest>()
            .Property(e => e.teamName)
            .IsUnicode(false);
    }
}

Here's the code from my xaml.cs file (view):

public async void GetBars()
{
    using (var client = new HttpClient())
    {
        barsListBox.Items.Add("using block entered");
        client.BaseAddress = new Uri("http://nflff.azurewebsites.net");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        barsListBox.Items.Add("client's defaultrequestheaders done");

        HttpResponseMessage response = await client.GetAsync("api/bars");
        barsListBox.Items.Add("httpresponsemessage object created with getasync");
        barsListBox.Items.Add(response.Content.ToString());

        if (response.IsSuccessStatusCode)
        {
            barsListBox.Items.Add("if entered");
            IList<Bars> bars = await response.Content.ReadAsAsync<IList<Bars>>();
            //successfully retrieves all bars items but need to format the printing
            //Wait... How can you instantiate a list ... to read itself? (Am I wrong) Nothing is being stored?
            //barsListBox.Items.Add(bars); //this just prints System.Collection.Generic...
            barsListBox.Items.Add(bars.Count); //list contains correct number of items
            for (int i = 0; i < bars.Count; i++)
            {
                barsListBox.Items.Add("for entered"); //iterating correct number of times
                barsListBox.Items.Add(i); //when printing bar[i], just prints empty object
            }
                //foreach (var bar in bars)
                //{
                //    barsListBox.Items.Add("foreach entered"); //not entering foreach
                //    barsListBox.Items.Add(bar.ToString());
                //}

            barsListBox.Items.Add("after foreach loop"); //getting printed
        }
        barsListBox.Items.Add("after if");
    }
}

And here's my (client-side) model's code:

class Bars 
{
    private int barID { get; set; }
    private string barName { get; set; }
    private string barStreet { get; set; }
    private string barCity { get; set; }
    private string barState { get; set; }
    private string barPhone { get; set; }
    private string barZip { get; set; }

    //public Bars()
    //{
    //    //empty constructor
    //}

    public override string ToString()
    {
        return "Bar: " + barID.ToString() +" " + barName.ToString() + " Phone: " + barPhone; //model obj not obtaining any values
    }
}

I'm at a complete loss as this is my first time creating a mobile app with a hosted database. At the moment, I'm getting the correct number of bars items returned from ReadAsAsync call in my view, but they're all empty. How can I get these Bars objects to contain their proper values? My database is a SQL database with a .NET back-end hosted on Azure web sites.

I figured out my problem. My code was actually working correctly. The problem was that when I deployed my database to an Azure website, it created a new database with the same tables and formats but without any data. When I ran my web api through the localhost, it worked fine because it was using a database that had my sample data in it, but the hosted database didn't so nothing would show up. To fix this, I imported the my sample data into the new hosted database and everything worked correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM