bikram s.
bikram s.

Reputation: 327

cast from List<EntityObject> to EntityObject

My code is as below.

public void CreateNewAuthor(List<Author> newAuthor)
{
    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()?

Upvotes: 0

Views: 278

Answers (3)

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);
    }
    

Upvotes: 1

Nathan Q
Nathan Q

Reputation: 1902

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

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499790

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?

Upvotes: 2

Related Questions