Upgrading Entity Framework 1.0 to 4.0 to include foreign keys

Posted by duthiega on Stack Overflow See other posts from Stack Overflow or by duthiega
Published on 2010-04-27T11:13:02Z Indexed on 2010/05/22 6:40 UTC
Read the original article Hit count: 221

Currently I've been working with Entity Framework 1.0 which is located under a service façade.

Below is one of the save methods I've created to either update or insert the device in question.

This currently works but, I can't help feel that its a bit of a hack having to set the referenced properties to null then re-attach them just to get an insert to work. The changedDevice already holds these values, so why do I need to assign them again.

So, I thought I'll update the model to EF4. That way I can just directly access the foreign keys. However, on doing this I've found that there doesn't seem to be an easy way to add the foreign keys except by removing the entity from the diagram and re-adding it. I don't want to do this as I've already been through all the entity properties renaming them from the DB column names. Can anyone help?

 /// <summary>
    /// Saves the non network device.
    /// </summary>
    /// <param name="nonNetworkDeviceDto">The non network device dto.</param>
    public void SaveNonNetworkDevice(NonNetworkDeviceDto nonNetworkDeviceDto)
    {
        using (var context = new AssetNetworkEntities2())
        {
            var changedDevice = TransformationHelper.ConvertNonNetworkDeviceDtoToEntity(nonNetworkDeviceDto);
            if (!nonNetworkDeviceDto.DeviceId.Equals(-1))
            {
                var originalDevice =
                context.NonNetworkDevices.Include("Status").Include("NonNetworkType").FirstOrDefault(
                  d => d.DeviceId.Equals(nonNetworkDeviceDto.DeviceId));
                context.ApplyAllReferencedPropertyChanges(originalDevice, changedDevice);
                context.ApplyCurrentValues(originalDevice.EntityKey.EntitySetName, changedDevice);
            }
            else
            {
                var maxNetworkDevice = context.NonNetworkDevices.OrderBy("it.DeviceId DESC").First();
                changedDevice.DeviceId = maxNetworkDevice.DeviceId + 1;
                var status = changedDevice.Status;
                var nonNetworkType = changedDevice.NonNetworkType;
                changedDevice.Status = null;
                changedDevice.NonNetworkType = null;
                context.AttachTo("DeviceStatuses", status);
                if (nonNetworkType != null)
                {
                    context.AttachTo("NonNetworkTypes", nonNetworkType);
                }

                changedDevice.Status = status;
                changedDevice.NonNetworkType = nonNetworkType;
                context.AddToNonNetworkDevices(changedDevice);
            }

            context.SaveChanges();
        }
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about entity-framework