Calculated attributes in model

Oct 27, 2014 at 9:21 AM
Edited Oct 27, 2014 at 9:40 AM
Hi

Having trouble update users in AD

My Model:
public class UserModel
{
    ....
    [ScaffoldColumn(false)]
    [DisplayName("Fødselsdag")]
    [DataType(DataType.Date)]
    [NotMapped]
    public DateTime extensionAttribute1_date
    {
    get
    {
         try
         {
              return DateTime.Parse(extensionAttribute1);
         }
         catch (Exception e)
         {
              return new DateTime();
          }
      }
      set { }
    }
    }
My Controller:
[HttpPost]
        public ActionResult Edit(string sAMAccountName, FormCollection collection, UserModel data)
        {
            if (ModelState.IsValid)
            {
                var config = new LdapConfiguration();
                config.ConfigureFactory("domain.local").AuthenticateAs(new NetworkCredential("xxxx", "xxxxx"));
                using (var context = new DirectoryContext(config))
                {
                    var user = context.Query(new UserModel(), "OU=users,OU=xxx,DC=xxx,DC=dk", "User").FirstOrDefault(d => d.sAMAccountName == sAMAccountName);
                    
                    if (user == null) return RedirectToAction("Index");

                    user.title = data.title;
                    user.mobile = data.mobile;
                    user.homePhone = data.homePhone;
                    user.streetAddress = data.streetAddress;
                    user.postalCode = data.postalCode;
                    user.l = data.l;
                    user.department = data.department;
                    user.physicalDeliveryOfficeName = data.physicalDeliveryOfficeName;
                    user.extensionAttribute1 = data.extensionAttribute1_date.ToLongDateString();

                    context.Update(user);
                }

                return RedirectToAction("Index");
            }

            return View();
        }
When i submit to Edit Action i results in an error:
The requested attribute does not exist.

If i remove extensionAttribute1_date from the model i updates fine.

How do i exclude my calculated attributes from the update?


I have other attributes in the model such as Age which is calculated! Is this the wrong procedure for this?


/Michael
Coordinator
Oct 29, 2014 at 10:34 PM
Hi Michael,

It looks like you're using auto-mapping for your model. Since you have the empty setter, LINQ to LDAP thinks that property is updatable. If you remove the empty setter then updating will work. If you can't remove the setter, you may want to think about converting it to a method or using attribute mapping.
Coordinator
Oct 29, 2014 at 10:38 PM
Also, just as a side note, you may want to use TryParse rather than catching the exception:
DateTime date;
if (DateTime.TryParse(extensionAttribute1, out date))
{
     return date;
}
else
{
     return new DateTime();
}