Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

c# - EF Code First not generating table for ICollection<string>

I would like the below ICollection property in one of my data classes (let's call it "Foo")

public class Foo
{
    [Key]
    public int FooId { get; set; }
    public string SomeValueOrOther { get; set; }
    public virtual ICollection<string> AllowedBars { get; set; }
}

I can add the string values when using the entity context, but they don't "go anywhere". In other words, no table is generated to represent this relationship and therefore no values are saved. What I would expect is a table with two columns, one for "FooId" and one for "AllowedBar" and for EF to map this to the collection automatically (as it does in with complex types).

As this doesn't happen, I've had to create a class called "FooAllowedBar" with the two properties I've described above.

This displeases me because it's the only "join" type class I have in the entire project. It works, of course, so one box is ticked, but does anybody know of a way to get EF to generate a table for the string collection relationship? (Or int, or datetime etc etc)

It may well be, from the little info that's out there on EF (still!) that this type of functionality is not (yet) supported. By I'd just like to get close to a definitive answer.

Many thanks in advance, Rob

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EF can only work with entity classes. Each entity class must have defined primary key so the minimum in your scenario is:

public class StringData
{
    public int Id { get; set; }
    public string Data { get; set; }
}

or worse

public class StringData
{
    [Key]
    public string Data { get; set; }
}

Now you can define collection of StringData to map it as related table:

public virtual ICollection<StringData> AllowedBars { get; set; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...