开发者

cast from List<EntityObject> to EntityObject

开发者 https://www.devze.com 2023-04-11 15:27 出处:网络
My code is as below. public void CreateNewAuthor(List<Author> ne开发者_Python百科wAuthor) { publishContext.AddToAuthors(newAuthor);

My code is as below.

public void CreateNewAuthor(List<Author> ne开发者_Python百科wAuthor)
{
    publishContext.AddToAuthors(newAuthor);
}

I know this will result in error as AddToAuthors(Author newAuthor) accepts entity object as parameter while I am passing a List<>. So how this should be handled? How to cast a List<> to entity object before AddToAuthors()?


You're accepting multiple authors - but you're trying to call something which takes a single author. Are you expecting multiple values within your list, or just a single one?

It sounds like you might just want to loop:

public void CreateNewAuthor(List<Author> newAuthors)
{
    foreach (Author newAuthor in newAuthors)
    {
        publishContext.AddToAuthors(newAuthor);
    }
}

... or it's entirely possible that the context already provides a way of adding multiple authors at a time. (I'm not an EF person, so I don't know for sure.)

The important thing is that you understand the possibilities here - the list could contain no authors, one author or multiple authors. Are all of those valid in your code? How do you want to handle each of those situations?


You could loop trough the list and add all the Author objects this list contains:

foreach (Author author in newAuthor)
{
    publishContext.AddToAuthors(author);
}


Case 1. You know that the list contains only one item:

  1. Change your method's signature to the following:

    public void CreateNewAuthor(Author newAuthor)
    

    (It is very unintuitive to refer to a list of items with a name that is not in the plural. It is even more unintuitive that your method accepts a list of (ie. "several") Author objects, yet requires that the list contain only one item.)

  2. Then, call your method as follows:

    // using System.Linq;
    // List<Author> someListOfAuthors = new List<Author> { someAuthor };
    CreateNewAuthor( someListOfAuthors.Single() );
    

    or, without using LINQ:

    CreateNewAuthor( someListOfAuthors[0] );
    

Case 2. The list may contain any number of items:

  1. Rename the parameter from newAuthor to newAuthors, for the same reason mentioned above.

  2. Change your method body to this:

    foreach (Author author in newAuthors)
    {
        publishContext.AddToAuthors(author);
    }
    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号