Reputation: 141
I'm building url shortener to improve my skills in ASP.NET Core, but came into a problem with using Entity Framework - .Find()
method always return null
from my database.
First of all, Im created db record class with custom Key field
public class DbField
{
[Key]
public string hash { get; set; }
public string link { get; set; }
}
Then applied it in a context
public class UrlShorterContext : DbContext
{
public DbSet<DbField> UrlHashes { get; set; }
public UrlShorterContext(DbContextOptions<UrlShorterContext> options)
: base(options)
{
Database.EnsureCreated();
}
}
Add context to services in ConfigureServices
with
string connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<UrlShorterContext>(options => options.UseSqlServer(connection));
And then applied it in a controller
UrlShorterContext db;
public HomeController(UrlShorterContext context)
{
db = context;
}
public IActionResult Index(string url,[FromServices] IComputeHash computeService)
{
string urlHash = computeService.Compute(url);//generates hash from url
DbField field = db.UrlHashes.Find(urlHash);
if (field == null)
{
db.UrlHashes.Add(new DbField { hash = urlHash, link = url });
return View("View1");
}
return View("View2");
...
In first run db is empty, action gets url, hashes it, add's to database and returns "View1".
In second run with same url it must be found in .Find()
method, field
must be assigned to its value and "View2" must be returned. But somehow field
get value of null
.
Upvotes: 1
Views: 1700
Reputation: 1514
After adding the hashed url to the UrlHashes DbSet, you need to call .SaveChanges()
to make sure the changes are written to the DB.
string urlHash = computeService.Compute(url);//generates hash from url
DbField field = db.UrlHashes.Find(urlHash);
if (field == null)
{
db.UrlHashes.Add(new DbField { hash = urlHash, link = url });
db.SaveChanges();
return View("View1");
}
return View("View2");
You should also look into making this action async and calling .SaveChangesAsync()
Upvotes: 3