0

I have built a Web API with the usual rest methods.

I have a field in my database for tracking when a record was inserted (called InsertLogtime. This works fine.

My classes are generated automatically by EF6 using database first.

I don't want this to be serialised so I added the [IgnoreDataMember] attribute to that field using the standard partial metadata classes...

[MetadataType(typeof(MembersMetaData))]
public partial class Members { }

public class MembersMetaData
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    [IgnoreDataMember]
    public Nullable<DateTime> InsertLogtime { get; set; }
}

Now when I use fiddler to put data into the other fields, the InsertLogTime field is set to null.

More importantly, I don't want to show every field for put. The customer only needs to use the Id and a single other field. However, they also need to provide a full dataset (without the InsertLogtime) when doing a full post.

{
"Id":99,
"FirstName":"Jack Spratt",
"EMail":"someone@somewhere.com",
"Eligible":false
}

This all works fine when doing a POST. Even the insert log time is ok as a quick and dirty measure I just set it in the controller using DateTime.Now. I know I should be using a default in the database but I'll get to it later.

Ideally I would like the customer to only have to insert the following when doing a PUT:

{
"Id":99,
"Eligible":true
}

But I am not sure how to do this. And as mentioned, when I use the full version that I use for POST when doing a PUT, it sets the InsertLogTime field to null.

Here is my controller

    [ResponseType(typeof(void))]
    public IHttpActionResult PutMembers(int id, Members members)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        if (id != members.Id)
            return BadRequest();

        eligible = members.Eligible ?? false;

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

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
                        //Notthing of interest here.
        }

        return StatusCode(HttpStatusCode.NoContent);
    }

Any help overcoming these problems would be really appreciated.

Francis Rodgers
  • 4,565
  • 8
  • 46
  • 65
  • Use an InputModel and then map only the needed fields to the related Entity to be saved correctly. You don't need to send everything to the client, given that you dont need It. Another way should be retrieve the entity and then set every changed field that was sent back – Fals Jul 23 '15 at 21:28
  • As well, the entity is not attached to the context, you should do something like: http://stackoverflow.com/questions/17790163/adding-and-updating-entities-with-entity-framework – Fals Jul 23 '15 at 21:31
  • @Fals - Thanks for the suggestions. Im looking over them now. The link isn't very clear, could you provide a quick example? – Francis Rodgers Jul 23 '15 at 22:07

0 Answers0