Ryan Griffith
Ryan Griffith

Reputation: 1640

Non-DB backed related objects in Entity Framework

I'm using Entity Framework 5 (code first method), and would like to have one of my Entities that is stored in my DB (and is exposed in my DbContext with an DbSet<> property) have a related object that is NOT stored in the DB.

Below is an example of what I'd like to achieve:

// Stored in DB
public class RecordedMeasure
{
    [Required]
    public int RecordedMeasureID { get; set; }

    [Required]
    [StringLength(150)]
    public string MeasureName { get; set; }

    // Navigation Property...
    // Go find the Measure by the MeasureName (which IS persisted to the DB)
    public Measure Measure { get; set;}

    // Additional properties removed for brevity....
}

// NOT Stored in DB
public class Measure{

    public string MeasureName { get; set;}
   
    // Additional properties removed for brevity....
}

// Allows registration and holds a static collection of all "Measures"
// that are known at runtime
public class MeasureRegistration{

    // Allow access to all measures stored
    public static List<Measure> Measures { get; set; }

    // Register a measure
    public static void Register(Measure measure) { 
        // Code removed for brevity...
    }
}

Is there a way to expose my MeasureRegistration.Measures collection as something that the Entity Framework can work with like it would a typical DbSet?

Thanks!

Update / Further Clarification

I am aware how to prevent the property from being Mapped to the database however, I am not aware of how to get EF to actually have a "Repository" or collection (like a DbSet<>) of NON DB-BACKED models that it can use to fulfill relationships between a DB-backed model and a non DB-backed model.

Upvotes: 1

Views: 202

Answers (2)

Mant101
Mant101

Reputation: 2747

Can't you just add a new property to the context that gives you an IEnumerable and put logic in the getter for retrieving it?

In your Context:

public IEnumerable<Measure> Measures { get { return MeasureRegistration.Measures; } }

In your entity:

[NotMapped]
public Measure Measure 
{ 
    get { return MeasureRegistration.Measures
                .FirstOrDefault(m => m.MeasureName == this.MeasureName; }
    set { this.MeasureName == value.MeasureName;}
}

From the question I gather you would like someway to for EF to hook this up for you in which case I think you are out of luck. I'm not sure what advantage that would have either on wiring it up yourself unless you have a bunch of entities referencing Measure.

Upvotes: 3

cheedep
cheedep

Reputation: 937

Using the [NotMapped] Annotation, you can achieve this.

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.notmappedattribute.aspx

"Denotes that a property or class should be excluded from database mapping."

Upvotes: 2

Related Questions