2

I am trying to define an EF Model containing a list or array of <string>. Using Add-Migration/Update-Database the field does not get added to the database table.

What I want is a field that would contain a comma-separated list of string values. There may be only a single value, or there could be 10 or more:

"Value1, Value2, ..."

I'd like to be able to use this field within my MVC5/EF6 web application as a key. For example:

IEnumerable<Param> params = 
    from u in _context.Params
    where u.MyValues.Contains("Value1") 
    select u;

I know this code is wrong, but here is what I am attempting:

public class Param
{
    public int Id { get; set; }
    public string[] MyValues { get; set; }
}

My DbSet:

public DbSet<Param> Params { get; set; }

The MyValues field doesn't get added to the schema and there are no errors thrown. Here is the Seed():

context.Params.Add(c => c.Id, new Param { MyValues = new[] { "Value1, Value2" } });

How can I add a field that contains a comma-separated list of string values that can then be accessed/queryied?

2
  • Do you want to use an array of strings, or a comma-separated list of values? You're trying to use both right now. Commented Jul 30, 2014 at 12:52
  • @Chris Hardie, I see that I included some code unintentionally. At first I was using IList<string> MyValues, but apparently EF6 will not create a database field of this type. I tried string[] as you can see, but that didn't generate a field either. I think Pragmateek provided some hints of how I can use a string to make it work. Commented Jul 30, 2014 at 23:24

1 Answer 1

2

As of now EF does not support custom conversions (maybe EF 7 will...) so you'll have to add some plumbing.

Here is what I typically do (there may be other better ways...):

private string myValuesAsString;
[Column("MyValues")]
public string MyValuesAsString
{
    get { return myValuesAsString; }
    set
    {
        myValuesAsString = value;
        myValues = value.Split(',');
    }
}

private string[] myValues;
[NotMapped]
public string[] MyValues
{
    get { return myValues; }
    set
    {
        myValues= value;
        myValuesAsString = string.Join(",", value);
    }
}

Not tested but you get the idea.

If you don't like the idea of adding public properties to your business entities you can:

  • inherit from your POCO business entities
  • use internal properties but mapping must then be done with the fluent API
  • use interfaces for a perfect abstraction
Sign up to request clarification or add additional context in comments.

1 Comment

You gave me a hint of how I can accomplish what I need using [NotMapped]. Thank you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.