Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7820763
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T07:25:22+00:00 2026-06-02T07:25:22+00:00

I have been developing the skeleton of a database that will support versioning of

  • 0

I have been developing the skeleton of a database that will support versioning of data using Code First in EF 4.3.1.

I had the models persisting and loading properly a couple of days ago but I have broken something since and I can’t figure out what is wrong. All of the classes get mapped and tables are created, data is persisted as well. So in the storring direction, everything works fine! BUT, when I try to load a Registration entity, the values are all what the default constructor is setting them to. I’m thinking maybe the data isn’t being loaded after the Registration constructor is called, but I’m at the end of my current abilities to figure out what’s happening!

The fundamentals are these two classes, from which my verion-able classes derive…

public abstract class VersionBase<T> {
    [Key]
    public Int64 Id { get; protected set; }
    public DateTime CreationDateTime { get; protected set; }

    // Value is virtual to support overriding to let deriving classes specify attributes for the property, such as [Required] to specify a non-nullable System.String
    public virtual T Value { get; internal set; }

    protected VersionBase() {
        CreationDateTime = DateTime.Now;
    }

    protected VersionBase(T value)
        : this() {
        Value = value;
    }
}

public abstract class VersionedBase<TVersion, TBase>
    where TVersion : VersionBase<TBase>, new() {
    [Key]
    public Int64 Id { get; protected set; }
    public virtual ICollection<TVersion> Versions { get; protected set; }

    protected VersionedBase() {
        Versions = new List<TVersion>();
    }

    [NotMapped]
    public Boolean HasValue {
        get {
            return Versions.Any();
        }
    }

    [NotMapped]
    public TBase Value {
        get {
            if (HasValue)
                return Versions.OrderByDescending(x => x.CreationDateTime).First().Value;
            throw new InvalidOperationException(this.GetType().Name + " has no value");
        }
        set {
            Versions.Add(new TVersion { Value = value });
        }
    }
}

Examples of derived classes…

public class VersionedInt32 : VersionedBase<VersionedInt32Version, Int32> { }

public class VersionedInt32Version : VersionBase<Int32> {
    public VersionedInt32Version() : base() { }
    public VersionedInt32Version(Int32 value) : base(value) { }
    public static implicit operator VersionedInt32Version(Int32 value) {
        return new VersionedInt32Version { Value = value };
    }
}

…and…

public class VersionedString : VersionedBase<VersionedStringVersion, String> { }

public class VersionedStringVersion : VersionBase<String> {
    public VersionedStringVersion() : base() { }
    public VersionedStringVersion(String value) : base(value) { }
    public static implicit operator VersionedStringVersion(String value) {
        return new VersionedStringVersion { Value = value };
    }

    /// <summary>
    /// The [Required] attribute tells Entity Framework that we want this column to be non-nullable
    /// </summary>
    [Required]
    public override String Value { get; internal set; }
}

My calling code is as such…

static void Main(String[] args) {
    using (var db = new VersionedFieldsContext()) {
        Registration registration = new Registration();
        registration.FirstName.Value = "Test";
        registration.FirstName.Versions.Add("Derp");
        db.Registration.Add(registration);
        db.SaveChanges();
    }
    using (var db = new VersionedFieldsContext()) {
        Registration registration = db.Registration.First();
        // InvalidOperationException at next line: "VersionedString has no value"
        String asdf = registration.FirstName.Value;
    }
}

public class Registration {
    [Key]
    public Int64 Id { get; set; }
    public DateTime CreationDateTime { get; set; }
    public VersionedString FirstName { get; set; }

    public Registration() {
        CreationDateTime = DateTime.Now;
        FirstName = new VersionedString();
    }
}

public class VersionedFieldsContext : DbContext {
    public DbSet<Registration> Registration { get; set; }

    public VersionedFieldsContext() {
        Database.SetInitializer<VersionedFieldsContext>(new DropCreateDatabaseIfModelChanges<VersionedFieldsContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

Thanks for any insight!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T07:25:23+00:00Added an answer on June 2, 2026 at 7:25 am

    You need two changes:

    • Remove instantiation of FirstName from the Registration constructor so that the constructor is only:

      public Registration() {
          CreationDateTime = DateTime.Now;
      }
      

      Creating an instance of a navigation reference (not collections) in an entity’s default constructor causes known problems: What would cause the Entity Framework to save an unloaded (but lazy loadable) reference over existing data?

    • If you have fixed the first point, your custom exception changes to a NullReferenceException. To fix this make the FirstName property in Registration virtual because the code in your second using block requires lazy loading:

      public virtual VersionedString FirstName { get; set; }
      

    Edit

    A workaround to create a registration and automatically instantiate the FirstName might be a factory method:

    public class Registration {
        [Key]
        public Int64 Id { get; set; }
        public DateTime CreationDateTime { get; set; }
        public VersionedString FirstName { get; set; }
    
        public Registration() {
            CreationDateTime = DateTime.Now;
        }
    
        public static Registration Create() {
            return new Registration {
                FirstName = new VersionedString()
            }
        }
    }
    

    EF uses the default constructor when it materializes a Registration object. In your custom code you could use the factory method when you need to create an instance of Registration:

    var registration = Registration.Create();
    

    It can be less useful though when you work with change tracking or lazy loading proxies and want to create a proxy instance manually:

    var registration = db.Registration.Create();
    

    This again will call the default constructor and you have to instantiate the FirstName after the object is already created.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been developing a Silverlight application using WCF. The problem is that sometimes
I have been developing a WCF project that will expose web services (HTTP-based) that
I have been developing applications that have a three-tier architecture and mostly using MVC
We have been developing code using loose coupling and dependency injection. A lot of
I have been developing Android application where I use this code: Date d=new Date(new
I have been developing a jquery widget that extends ui.mouse. The widget needs to
I have been developing a book viewing website that takes rather large images (upwards
I have been developing an app using the very easy-to-pickup Flask system and I
I have been developing my first mobile site with jQuery Mobile and you can
I have been developing some Django app and there's some duplicated code for different

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.