A
A
Alexander Dubina2016-10-07 15:54:11
.NET
Alexander Dubina, 2016-10-07 15:54:11

Entity framework core many to many, how to work with data?

I'm studying .net core, I ran into a problem that many-to-many in Entity framework core is not normally supported.
I found a kind of solution ,
but I don’t understand how to save or get related data.
MyContext .Posts .Where (z=>z.PostTags ) .....
and what next?
Well, how to save a post attached to many tags?
I will be grateful for help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Dubina, 2016-10-07
@struggleendlessly

M_News m_News = new M_News();
                m_News.Title = vm_News.Title;
                m_News.Text = vm_News.Text;
                m_News.IsActive = vm_News.IsActive;
                m_News.DateCreated = vm_News.DateCreated;

                m_News.P_CategoryNews = new List<M_CategoryNews>();

                //_context.Add(m_News);

                

                foreach (var item in vm_News.CategoriesListSelected)
                {
                    M_CategoryNews MTM = new M_CategoryNews();
                    MTM.M_News = m_News;

                    M_Category category = _context.db_Category.SingleOrDefault(z => z.IDCategory == item);
                    MTM.M_Category = category;

                    _context.Add(MTM);
                }            
                
                await _context.SaveChangesAsync();

R
Roman, 2016-10-09
@yarosroman

Everything is supported, for getting there is Include, For example Posts.Where(w=>w.Id==1).Include(i=>i.Tags).
Post.Tags=new HashSet;
Post.Tags.Add(new Tag());
context.SaveChanges();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question