I have Models:
public class TVProgram
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<Channel> Channels { get; set; }
}
public class Channel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int Created { get; set; }
}
When i saved data to database it should be a lot of TV Channels connected to specify TVPrograms.
For example i need to have program named "Animals Life" on Channels "Discovery, Animal Pl.net, BBC", but in database its saved with last added id, for example:
ID | Name | TVProgramID
0 | AL | 4
0 | AL2 | 4
Where 4 is id of last updated Program TV.
I expect something like
ID | Name | TVProgramIDs
0 | AL | 1,2,3
0 | AL2 | 2,4,9
Im using context like:
using(var cnx = new MyContext())
{
var channel = cnx.Channels.Where(x => x.Name == "AL").FirstOrDefault();
var program = cnx.Programs.Where(x => x.Name == "Discovery").Include(x=>x.Channels).FirstOrDefault();
program.Channels.Add(channel);
program.SaveChanges();
}
How to fix that?
You are missing a 'many to many' table between TVProgram and Channel. In EF this is (or used to be) automatic, but in EF core you need to do this manually.
public class TVProgram
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<TVProgramChannel> TVProgramChannels { get; set; }
}
public class Channel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int Created { get; set; }
public List<TVProgramChannel> TVProgramChannels { get; set; }
}
public class TVProgramChannel
{
public TVProgram TVProgram {get;set;}
public Channel Channel {get;set;}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.