You can not implicitly convert "RESTfullApi.Models.Product []" to "RESTfullApi.Models.Product" - c#

i'm trying to learn how to create Web Api, and i have an error.
I don't know what to do, first it required to use sufix M when i used it, VS show me error:
You cannnot implicitly convert "RESTfullApi.Models.Product []" to
"RESTfullApi.Models.Product"
I was trying to find answer on the internet but nothing explain this case.
Maybe you know what is wrong with it?
This is tutorial in which i practice:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
ProductsController.cs
using RESTfullApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace RESTfullApi.Controllers
{
public class ProductsController : ApiController
{
Product products = new Product[]
{
new Product { Id = 1, Name = "Pizza Margarita", Category = "Pizza", Price = 13.00M },
new Product { Id = 2, Name = "Pizza Double Cheese", Category = "Pizza", Price = 17.00M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
}
}
Product.cs (Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RESTfullApi.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}

Message is self explanatory. Change products to
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Pizza Margarita", Category = "Pizza", Price = 13.00M },
new Product { Id = 2, Name = "Pizza Double Cheese", Category = "Pizza", Price = 17.00M }
};

Related

I am getting an error while producing objects

I'm developing a project with N-tier architecture. I got errors while generating a new object in the main function.I can not give the features of car1. The entire text is underlined in red and I get these errors "CS1922: Cannot initialize type 'Car' with a collection initializer because it does not implement 'System.Collections.IEnumerable'" and "CS0747: Invalid initializer member declator".
using Business.Concrete;
using System;
using Entities.Concrete;
using DataAccess.Concrete.EntityFramework;
static void Main(string[] args)
{
Car car1 = new Car
{
car1.Id = 4,
car1.BrandId = 1,
car1.ColourId = 2,
car1.ModelYear = 1990,
car1.Name = "King",
car1.DailyPrice = 150,
car1.Description = "Best"
};
CarManager carManager = new CarManager(new EfCarDal());
Console.ReadLine();
}
Entities\Concrete\Car.cs
using Core.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace Entities.Concrete
{
public class Car : IEntity
{
public int Id { get; set; }
public int BrandId { get; set; }
public int ColourId { get; set; }
public string Name { get; set; }
public int ModelYear { get; set; }
public int DailyPrice { get; set; }
public string Description { get; set; }
}
}
You don't need the car1. access when initializing within {} like so:
Car car1 = new Car
{
Id = 4,
BrandId = 1,
ColourId = 2,
ModelYear = 1990,
Name = "King",
DailyPrice = 150,
Description = "Best"
};

mongodb graphLookup c# example with POCO classes

Is there any chance to use graphLookup aggregate stage with POCO classes and not bson documents?
All examples I've found are using BsonDocuments and it makes me really confused.
Thanks.
let's take the example scenario of wanting to get back a breadcrumb result for a given category in a library...
here's a full program that inserts some seed data and uses a graphlookup aggregation stage to get the breadcrumb for the Mindfulness category:
note: i've used MongoDB.Entities library for brevity. the aggregate query would be the same for the official driver.
using MongoDB.Driver;
using MongoDB.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace TestApplication
{
public class Category : Entity
{
public string Name { get; set; }
public string ParentCategory { get; set; }
}
public class Result
{
public string[] BreadCrumb { get; set; }
}
public static class Program
{
private static async Task Main()
{
await DB.InitAsync("test");
await new[] {
new Category { Name = "Books" },
new Category { Name = "Sci-Fi", ParentCategory = "Books" },
new Category { Name = "Space", ParentCategory = "Sci-Fi" },
new Category { Name = "AI", ParentCategory = "Sci-Fi" },
new Category { Name = "Self-Help", ParentCategory = "Books" },
new Category { Name = "Mindfulness", ParentCategory = "Self-Help" },
new Category { Name = "Hypnotherapy", ParentCategory = "Self-Help" }
}.SaveAsync();
var collection = DB.Collection<Category>();
var result = await collection.Aggregate()
.Match(c => c.Name == "Mindfulness")
.GraphLookup<Category, string, string, string, Category, IEnumerable<Category>, object>(
from: collection,
connectFromField: nameof(Category.ParentCategory),
connectToField: nameof(Category.Name),
startWith: $"${nameof(Category.Name)}",
#as: "BreadCrumb",
depthField: "order")
.Unwind("BreadCrumb")
.SortByDescending(x => x["BreadCrumb.order"])
.Group("{_id:null, BreadCrumb:{$push:'$BreadCrumb'}}")
.Project("{_id:0, BreadCrumb:'$BreadCrumb.Name'}")
.As<Result>()
.ToListAsync();
var output = string.Join(" > ", result[0].BreadCrumb);
Console.WriteLine(output); //Books > Self-Help > Mindfulness
Console.ReadLine();
}
}
}

Does the MongoDB C# driver support Joins of this manner?

I have two classes Person and Animal
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace MongoTesting.Documents
{
public class Person
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public Guid PersonId { get; set; } = Guid.NewGuid();
public Guid PetId { get; set; } = Guid.Empty;
public string Name { get; set; } = "Person";
}
}
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace MongoTesting.Documents
{
public class Animal
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public Guid AnimalId { get; set; } = Guid.NewGuid();
public bool IsMammal { get; set; }
public string Description { get; set; } = "Animal";
}
}
Which are serialized into IMongoCollections
public IMongoCollection<Person> PersonCollection { get; set; }
public IMongoCollection<Animal> AnimalCollection { get; set; }
...
PersonCollection = Database.GetCollection<Person>("PersonCollection");
AnimalCollection = Database.GetCollection<Animal>("AnimalCollection");
Using the C# 2.7.0 MongoDB .Net driver and the MongoDB 3.4 mongod server daemon.
I am trying to write a specific type of query given this setup, specifically the one in the SSCCE below
using System;
using System.Linq;
using System.Collections.Generic;
using MongoTesting.Documents;
using MongoTesting.DatabaseInterface;
using MongoDB.Driver;
namespace MongoTesting
{
class Program
{
static void Main(string[] args)
{
MongoInterface _mongo = new MongoInterface();
_mongo.Open();
//CreateDocuments(_mongo);
Console.Out.WriteLine("Total Persons: " + _mongo.PersonCollection.CountDocuments(Builders<Person>.Filter.Empty));
Console.Out.WriteLine("Total Animals: " + _mongo.AnimalCollection.CountDocuments(Builders<Animal>.Filter.Empty));
var peopleWithMammalianPetsQuery =
from person in _mongo.PersonCollection.AsQueryable()
join animal in _mongo.AnimalCollection.AsQueryable() on person.PetId equals animal.AnimalId
where animal.IsMammal
select person;
var peopleWithMammalianPets = peopleWithMammalianPetsQuery.ToList();
peopleWithMammalianPets.ForEach(person => { Console.Out.WriteLine("Person: " + person.Name); });
Console.ReadLine();
}
public static void CreateDocuments(MongoInterface _mongo)
{
Animal dog = new Animal() { IsMammal = true, Description = "Dog" };
Animal cat = new Animal() { IsMammal = true, Description = "Cat" };
Animal bird = new Animal() { IsMammal = false, Description = "Bird" };
Animal snake = new Animal() { IsMammal = false, Description = "Snake" };
Person bob = new Person() { PetId = dog.AnimalId, Name = "Bob" };
Person sue = new Person() { PetId = cat.AnimalId, Name = "Sue" };
Person sam = new Person() { PetId = bird.AnimalId, Name = "Sam" };
Person eve = new Person() { PetId = snake.AnimalId, Name = "Eve" };
_mongo.PersonCollection.InsertMany(new List<Person>() { bob, sue, sam, eve });
_mongo.AnimalCollection.InsertMany(new List<Animal>() { dog, cat, bird, snake });
}
}
}
Where MongoInterface represents a class which can connect to the MongoDB server, get access to the IMongoDatabase, and manipulate PersonCollection and AnimalCollection.
My specific issue with the code above, is that, when ran the following exception is thrown during the execution of the peopleWithMammalianPetsQuery.
An unhandled exception of type 'System.NotSupportedException' occurred in
MongoDB.Driver.dll
Additional information: $project or $group does not support {document}.
I have searched around and I cannot find something the exactly duplicates this issue and solves it. There are many reports of the exception message though they all seem to differ in the usage which produced it (even some seem to have been fixed). I have also seen multiple posts showing very similar code (specifically a join) working without issue.
How can I perform the query described above?

C# SQLite Extensions InsertWithChildren doesn't work why?

i have a Problem with my SQLite-Database. I use the SQLite.Net and SQLiteNetExtensions PCL NuGets and followed this excample: Link
I have a connection and it insert a stock but not the valuation list.
My copy paste code:
var valuation1 = new Valuation
{
Price = 15,
Time = DateTime.Now,
};
var valuation2= new Valuation
{
Price = 22,
Time = DateTime.Now,
};
var euro = new Stock
{
Symbol = "€",
Valuations = new List<Valuation> { valuation1, valuation2 }
};
connection.CreateTable<Stock>();
connection.CreateTable<Valuation>();
connection.InsertWithChildren(euro);
var stockList = c.GetAllWithChildren<Stock>();
In Stocklist is a Stock but in Stock is no Valuation :(
usings:
using System; using System.Collections.Generic;
using System.Linq;
using SQLiteNetExtensions.Extensions;
using TestSQLite.Models;
Models:
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;
using System;
using System.Collections.Generic;
public class Stock
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(8)]
public string Symbol { get; set; }
[OneToMany] // One to many relationship with Valuation
public List<Valuation> Valuations { get; set; }
}
using SQLite.Net.Attributes;
using SQLiteNetExtensions.Attributes;
using System;
public class Valuation
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ForeignKey(typeof(Stock))] // Specify the foreign key
public int StockId { get; set; }
public DateTime Time { get; set; }
public decimal Price { get; set; }
[ManyToOne] // Many to one relationship with Stock
public Stock Stock { get; set; }
}
Any ideas or suggestions what i could do to make it work?
EDIT:
I just tried some things and if i inseret it by my self like this:
c.Insert(euro);
var e = c.Find<Stock>(s => s.Symbol == "€");
var valuation1 = new Valuation
{
Price = 15,
Time = DateTime.Now,
StockId = e.StockId,
Stock = e
};
var valuation2 = new Valuation
{
Price = 22,
Time = DateTime.Now,
StockId = e.StockId,
Stock = e
};
c.Insert(valuation1);
c.Insert(valuation2);
var stockList = c.GetAllWithChildren<Stock>();
i get a correct stock "euro" and valutations in it! What is my mistake at InsertWithChildren? Or is there anything wrong with my models?

Send List to Controller using interface?

I have my Product class, which is pretty straight forward, Then I want to use an Interface to send a List of Product objects over the to Controller.
I think Im good to go with my Product class and IProduct interface ?
my problems:
In MYcontext class, I am trying to make the list, but IM not really sure how to proceed.
and MyRepository class should send the List to the Controller eventually.
My purpose of using the interface is just really for practice.. and I will do some Testing later too.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Uppgift_1.Models
{
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public double PriceBuy { get; set; }
public double PriceSell { get; set; }
public double Moms { get; set; }
public Product()
{
}
public Product(int productId, string productName, double priceBuy, double priceSell, double moms)
{
ProductId = productId;
ProductName = productName;
PriceBuy = priceBuy;
PriceSell = priceSell;
Moms = moms;
}
// TODO: add calculation method
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Uppgift_1.Models
{
public interface IProduct
{
IQueryable<Product> Products { get; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Uppgift_1.Models
{
public class MYcontext : Product
{
IQueryable<Product> Products = new List<Product>();
Product p1 = new Product(21, "RollerSkates", 82.5, 164, 1.25);
Product p2 = new Product(22, "Fridge", 88, 844, 1.25);
Product p3 = new Product(23, "TV", 182.5, 364, 1.25);
Product p4 = new Product(24, "Boat", 325, 64, 1.25);
Product p5 = new Product(25, "Car", 22.5, 74, 1.25);
Product p6 = new Product(26, "Magasine", 84.3, 44, 1.25);
Product p7 = new Product(27, "Garage", 182.7, 843, 1.25);
Product p8 = new Product(28, "House", 182.8, 542, 1.25);
Product p9 = new Product(29, "Beach", 814.9, 62, 1.25);
Product p10 = new Product(30, "Ball", 69.3, 16, 1.25);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Uppgift_1.Models
{
public class MyRepository : IProduct
{
public IQueryable<Product> Products
{
get { return MYcontext.pList; }
}
}
}
You need to add getData logic to your repository like this(check Context Products, im not sure about it) :
public class MyRepository : IProduct
{
public IQueryable<Product> Products
{
get { return MYcontext.pList; }
}
public IQueryable<Product> GetProducts() {
return (from obj in Products select obj).FirstOrDefault();
}
}
And your interface
namespace Uppgift_1.Models
{
public interface IProduct
{
IQueryable<Product> GetProducts();
}
}
And in Controller you could use it like this:
public MyController:Controller {
IProduct<Product> service = new MyRepository();
public ActionResult Index() {
var prods = service.GetProducts();
return View(prods) ;
}
}

Categories

Resources