Rafael Carvalho
Rafael Carvalho

Reputation: 91

ASP.NET MVC Image Upload and create records on database with Entity Framework

Well im working with Xamarin and I have a WebAPI using Entity Framework. I can already send the images from phone to the webservice but I want to create the records on the database with all the relationships correctly, so basically I have 3 tables to work, as below:

  1. Image
  2. OccurenceImage
  3. Occurence

Model Diagram

In my WebAPI I have two controllers, one to handle the image uploads and another to handle the Occurences. I tried to set a custom ID when I create the record of OccurenceImage but it doesn't work.

ImageUploadController.cs

[HttpPost]
        public HttpResponseMessage UploadImage(string imageName)
        {
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            if (Request.Content.IsMimeMultipartContent())
            {
                Request.Content.LoadIntoBufferAsync().Wait();
                Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
                {
                    MultipartMemoryStreamProvider provider = task.Result;
                    foreach (HttpContent content in provider.Contents)
                    {
                        Stream stream = content.ReadAsStreamAsync().Result;
                        Image image = Image.FromStream(stream);
                        var testName = content.Headers.ContentDisposition.Name;
                        String filePath = HostingEnvironment.MapPath("~/Images/");
                        string nameImg = imageName + Guid.NewGuid();
                        String fullPath = Path.Combine(filePath, nameImg + ".jpg");
                        image.Save(fullPath);
                        AddImageToDb(nameImg);
                    }
                });

                return result;
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
            }

        }

        private void AddImageToDb(string imageName)
        {
            VisitDatabase.Image image = new VisitDatabase.Image()
            {
                urlImage = imageName + ".jpg"
            };

            OccurenceImage occurenceImage = new OccurenceImage()
            {
               idOccurence = 18,
               Image = image,

            };
            db.Image.Add(image);
            db.OccurenceImage.Add(occurenceImage);
            db.SaveChanges();
        }


OccurenceController.cs

[ResponseType(typeof(ActiveCitizen))]
        public IHttpActionResult PostOccurence(ActiveCitizen json)
        {
            Citizen citizen;
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            ActiveCitizen activeCitizen = json;
            var query = (from c in db.Citizen
                where c.ccbi == activeCitizen.NumDocument
                select c.idCitizen).SingleOrDefault();
            Address address = new Address()
            {
                lat = 12,
                lon = 12,
                street = "Rua do Santuario",
                postalCode = "4490-554",
                locality = "Barcelos"
            };


            OccurenceType occurenceType = new OccurenceType()
            {
                title = activeCitizen.Description,               
            };
            if (query == 0)
            {
                citizen = new Citizen()
                {
                    ccbi = activeCitizen.NumDocument,
                    nif = activeCitizen.NIF,
                    Contact = new Contact()
                    {
                        name = activeCitizen.Name,
                        email = activeCitizen.Email,
                        phone = activeCitizen.Phone
                    },
                    Address = address
                };
            }
            else
            {
                citizen = db.Citizen.Find(query);
            }                   

            Occurence occurence = new Occurence()
            {
                solved = 0,
                occurenceDateTime = new DateTime(2017, 5, 23),
                Address = address,
                OccurenceType = occurenceType,
                Citizen = citizen
            };

            db.Address.Add(address);
            db.OccurenceType.Add(occurenceType);
            if (query == 0)
            {
                db.Contact.Add(citizen.Contact);
                db.Citizen.Add(citizen);
            }           
            db.Occurence.Add(occurence);
            db.SaveChanges();
            return CreatedAtRoute("DefaultApi", new { id = occurence.idOccurence }, activeCitizen);
        }


Thanks in advance!

Upvotes: 4

Views: 939

Answers (1)

Rafael Carvalho
Rafael Carvalho

Reputation: 91

The code above is correct, seems like the problem was on the table OccurenceImage the field idOccurenceImage Identity Specification was disabled, just needed to enable and worked like a charm. I hope this helps another people with this kind of newbie problems!

Upvotes: 5

Related Questions