3

I've been trying to map a one-to-many, one-way relationship using EF 4.1 code-first, e.g. User has Address but Address knows nothing about User. This is straightforward to implement either with a ForeignKey attribute or a fluent api (shown in included code).

The problem comes when adding a Version (byte[]) column with a Timestamp attribute on both mapped classes. If we now create an instance of a User that has a reference to an existing (in the db) Address and add it to the context, upon calling SaveChanges a database profiler will show two database queries, one that is the User insert and the other is an update to the Address table to change the Version. Not what I want. If I've modelled no relationship in my domain then I don't want any version change either. I only want a version change on Address if I change an Address instance.

I suspect that because the mapping is using HasMany(), internally the EF DbContext believes there is a collection that needs to be satisified and as the collection has changed (by adding a new User) it automagically updates the version of Address. All this despite the fact Address has no collection property of type ICollection<User>.

So to my question. What mapping do I need to put in place for the relationship to maintain the class structures as they are without having the Address version change when I add a new User?

EDIT: I've found that the only way I can prevent the update of the version on Address is to reduce the mapping to an HasRequired(a => a.Address) only and no longer have the AddressId foreign key on the User class. It seems if the foreign key "property" is on User either explicit mapping or convention mapping will ensure the version of Address is updated.

I would prefer to apply some extension to HasRequired to tell the context how to treat the relationship rather than having to remove the foreign key property entirely.

Here's the code I use to demonstrate the problem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace DbTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Address address = null;

            // Make sure we have one address to test with
            using (var context = new DemoContext())
            {
                address = context.Addresses.FirstOrDefault();
                if (address == null)
                {
                    address = new Address { Street = "My Street" };
                    context.Addresses.Add(address);
                    context.SaveChanges();
                }
            }

            byte[] version = address.Version;

            using (var context = new DemoContext())
            {
                // Uncomment to test attaching
                // context.Addresses.Attach(address);
                address = context.Addresses.FirstOrDefault();

                var user = new User { Name = "Mark", Address = address };
                context.Users.Add(user);
                context.SaveChanges(); // Results in new user inserted and a version update to the Address referenced object
            }

            using (var context = new DemoContext())
            {
                var address2 = context.Addresses.FirstOrDefault();
                Console.WriteLine("Versions: {0}, {1}", BitConverter.ToString(version), BitConverter.ToString(address2.Version));
            }

            Console.ReadLine();
        }
    }

    public class User
    {
        [Key]
        public int UserId { get; set; }
        public string Name { get; set; }
        public int AddressId { get; set; }

//        [ForeignKey("AddressId")]
        public Address Address { get; set; }

        [Timestamp]
        public byte[] Version { get; set; }
    }

    public class Address
    {
        [Key]
        public int AddressId { get; set; }
        public string Street { get; set; }
        [Timestamp]
        public byte[] Version { get; set; }
    }

    public class DemoContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Address> Addresses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
                        .HasRequired(a => a.Address)
                        .WithMany()
                        .HasForeignKey(u => u.AddressId);
        }
    }
}

2 Answers 2

0

A workaround:

Leverage your exposed foreign key and replace this code...

address = context.Addresses.FirstOrDefault();
var user = new User { Name = "Mark", Address = address };

...by:

var addressId = context.Addresses.Select(a => a.AddressId).FirstOrDefault();
var user = new User { Name = "Mark", AddressId = addressId };

This doesn't change the timestamp of the address entity.

I don't think that there is any mapping option to avoid the UPDATE statement of the address in your original code. I would follow your hypothesis that EF considers your code as a change of a relationship between users and address and therefore updates the address, no matter if the user collection is exposed in the Address model or not.

2
  • 1
    Whilst that works it is only useful when the Address if not already in the context. If it is in the context the version will be updated.
    – Mark
    Dec 22, 2011 at 0:37
  • ...so check for it and detatch the Address from the context first. Apr 8, 2015 at 13:44
0

I've found that the only way I can prevent the update of the version on Address is to reduce the mapping to an HasRequired(a => a.Address) only and no longer have the AddressId foreign key on the User class. It seems if the foreign key "property" is on User either explicit mapping or convention will ensure the version of Address is updated.

I would prefer to apply some extensino to HasRequired to tell the context how to treat the relationship rather than having to remove the foreign key property entirely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.