C#FluentAPI很多人都使用EF

时间:2017-11-02 18:41:10

标签: database many-to-many

在尝试连接数据库时遇到有关多对多关系的问题。当我将数据添加到数据库中的多对多表时,问题就出现了。 (数据库是Windows SQL)

的DataModel:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace PublisherDataModel
{
    public class Book
    {
        public Book()
        {
            this.Authors = new HashSet<Author>();
        }
        public int BookId { get; set; }

        [Required]
        [StringLength(250)]
        public string Title { get; set; }

        public virtual ICollection<Author> Authors { get; set; }
    }

    public class Author
    {
        public Author()
        {
            this.Books = new HashSet<Book>();
        }

        public int AuthorId { get; set; }

        [Required]
        [StringLength(250)]
        public string Name { get; set; }

        public virtual ICollection<Book> Books { get; set; }
    }

    public class PublisherEntities : DbContext
    {
        public DbSet<Book> Books { get; set; }
        public DbSet<Author> Authors { get; set; }

        public PublisherEntities()
            : base(@"DatabaseConnection")
        {
            this.Configuration.ProxyCreationEnabled = false;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Book>()
                   .HasMany<Author>(b => b.Authors)
                   .WithMany(a => a.Books)
                   .Map(ab =>
                   {
                       ab.MapLeftKey("BookRefId");
                       ab.MapRightKey("AuthorRefId");
                       ab.ToTable("BookAuthor");
                   });
        }
    }
}

和作者和书籍的控制器(仅发布一个)

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Description;
using PublisherDataModel;

namespace PublisherDataService.Controllers
{
    public class AuthorsController : ApiController
    {
        private PublisherEntities db = new PublisherEntities();

        // GET api/Authors
        public IQueryable<Author> GetAuthors()
        {
            return db.Authors.Include(a => a.Books);
        }

        // GET api/Authors/5
        [ResponseType(typeof(Author))]
        public IHttpActionResult GetAuthor(int id)
        {
            Author author = db.Authors.Find(id);
            if (author == null)
            {
                return NotFound();
            }

            return Ok(author);
        }

        // PUT api/Authors/5
        public IHttpActionResult PutAuthor(int id, Author author)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != author.AuthorId)
            {
                return BadRequest();
            }

            db.Entry(author).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AuthorExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST api/Authors
        [ResponseType(typeof(Author))]
        public IHttpActionResult PostAuthor(Author author)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Authors.Add(author);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = author.AuthorId }, author);
        }

        // DELETE api/Authors/5
        [ResponseType(typeof(Author))]
        public IHttpActionResult DeleteAuthor(int id)
        {
            Author author = db.Authors.Find(id);
            if (author == null)
            {
                return NotFound();
            }

            db.Authors.Remove(author);
            db.SaveChanges();

            return Ok(author);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool AuthorExists(int id)
        {
            return db.Authors.Count(e => e.AuthorId == id) > 0;
        }
    }
}

没有数据添加到多对多表时的结果: Result before adding data to the table

将数据添加到多对多表中的结果: Result after adding data to the table

无论是否将数据添加到多对多表中,它都会出现错误,它应该说明您应该期望的信息以及它应该采用的格式。 Format error

那么我在这里做错了什么,DataModel中的多对多关系是否存在问题?根据我的理解,ICollection应该是导航属性。

另外,您如何从浏览器获取多对多的信息?我看到了一些使用/ api / Authors / 4 / Books的例子,但是当你在尝试在数据库中添加多个数据时遇到错误时,这个例子不起作用。

感谢。很高兴在需要时添加更多信息。

0 个答案:

没有答案